Code Summary
Prisma
Source: my-backend/node_modules/.prisma/client/edge.js
Signature: Prisma(.TransactionIsolationLevel = makeStrictEnum({
ReadUncommitted: 'ReadUncommitted',
ReadCommitted: 'ReadCommitted',
RepeatableRead: 'RepeatableRead',
Serializable: 'Serializable'
})
JSDoc:
Prisma Client JS version: 6.16.3 Query Engine version: bb420e667c1820a8c05a38023385f6cc7ef8e83a / Prisma.prismaVersion = { client: "6.16.3", engine: "bb420e667c1820a8c05a38023385f6cc7ef8e83a" }
Prisma.PrismaClientKnownRequestError = PrismaClientKnownRequestError; Prisma.PrismaClientUnknownRequestError = PrismaClientUnknownRequestError Prisma.PrismaClientRustPanicError = PrismaClientRustPanicError Prisma.PrismaClientInitializationError = PrismaClientInitializationError Prisma.PrismaClientValidationError = PrismaClientValidationError Prisma.Decimal = Decimal
/** Re-export of sql-template-tag / Prisma.sql = sqltag Prisma.empty = empty Prisma.join = join Prisma.raw = raw Prisma.validator = Public.validator
/** Extensions / Prisma.getExtensionContext = Extensions.getExtensionContext Prisma.defineExtension = Extensions.defineExtension
/** Shorthand utilities for JSON filtering / Prisma.DbNull = objectEnumValues.instances.DbNull Prisma.JsonNull = objectEnumValues.instances.JsonNull Prisma.AnyNull = objectEnumValues.instances.AnyNull
Prisma.NullTypes = { DbNull: objectEnumValues.classes.DbNull, JsonNull: objectEnumValues.classes.JsonNull, AnyNull: objectEnumValues.classes.AnyNull }
/** Enums
Prisma
Source: my-backend/node_modules/.prisma/client/index-browser.js
Signature: Prisma(.TransactionIsolationLevel = makeStrictEnum({
ReadUncommitted: 'ReadUncommitted',
ReadCommitted: 'ReadCommitted',
RepeatableRead: 'RepeatableRead',
Serializable: 'Serializable'
})
JSDoc:
Prisma Client JS version: 6.16.3 Query Engine version: bb420e667c1820a8c05a38023385f6cc7ef8e83a / Prisma.prismaVersion = { client: "6.16.3", engine: "bb420e667c1820a8c05a38023385f6cc7ef8e83a" }
Prisma.PrismaClientKnownRequestError = () => {
const runtimeName = getRuntime().prettyName;
throw new Error(PrismaClientKnownRequestError is unable to run in this browser environment, or has been bundled for the browser (running in ${runtimeName}).
In case this error is unexpected for you, please report it in https://pris.ly/prisma-prisma-bug-report,
)};
Prisma.PrismaClientUnknownRequestError = () => {
const runtimeName = getRuntime().prettyName;
throw new Error(PrismaClientUnknownRequestError is unable to run in this browser environment, or has been bundled for the browser (running in ${runtimeName}).
In case this error is unexpected for you, please report it in https://pris.ly/prisma-prisma-bug-report,
)}
Prisma.PrismaClientRustPanicError = () => {
const runtimeName = getRuntime().prettyName;
throw new Error(PrismaClientRustPanicError is unable to run in this browser environment, or has been bundled for the browser (running in ${runtimeName}).
In case this error is unexpected for you, please report it in https://pris.ly/prisma-prisma-bug-report,
)}
Prisma.PrismaClientInitializationError = () => {
const runtimeName = getRuntime().prettyName;
throw new Error(PrismaClientInitializationError is unable to run in this browser environment, or has been bundled for the browser (running in ${runtimeName}).
In case this error is unexpected for you, please report it in https://pris.ly/prisma-prisma-bug-report,
)}
Prisma.PrismaClientValidationError = () => {
const runtimeName = getRuntime().prettyName;
throw new Error(PrismaClientValidationError is unable to run in this browser environment, or has been bundled for the browser (running in ${runtimeName}).
In case this error is unexpected for you, please report it in https://pris.ly/prisma-prisma-bug-report,
)}
Prisma.Decimal = Decimal
/**
Re-export of sql-template-tag
/
Prisma.sql = () => {
const runtimeName = getRuntime().prettyName;
throw new Error(sqltag is unable to run in this browser environment, or has been bundled for the browser (running in ${runtimeName}).
In case this error is unexpected for you, please report it in https://pris.ly/prisma-prisma-bug-report,
)}
Prisma.empty = () => {
const runtimeName = getRuntime().prettyName;
throw new Error(empty is unable to run in this browser environment, or has been bundled for the browser (running in ${runtimeName}).
In case this error is unexpected for you, please report it in https://pris.ly/prisma-prisma-bug-report,
)}
Prisma.join = () => {
const runtimeName = getRuntime().prettyName;
throw new Error(join is unable to run in this browser environment, or has been bundled for the browser (running in ${runtimeName}).
In case this error is unexpected for you, please report it in https://pris.ly/prisma-prisma-bug-report,
)}
Prisma.raw = () => {
const runtimeName = getRuntime().prettyName;
throw new Error(raw is unable to run in this browser environment, or has been bundled for the browser (running in ${runtimeName}).
In case this error is unexpected for you, please report it in https://pris.ly/prisma-prisma-bug-report,
)}
Prisma.validator = Public.validator
/**
Extensions
/
Prisma.getExtensionContext = () => {
const runtimeName = getRuntime().prettyName;
throw new Error(Extensions.getExtensionContext is unable to run in this browser environment, or has been bundled for the browser (running in ${runtimeName}).
In case this error is unexpected for you, please report it in https://pris.ly/prisma-prisma-bug-report,
)}
Prisma.defineExtension = () => {
const runtimeName = getRuntime().prettyName;
throw new Error(Extensions.defineExtension is unable to run in this browser environment, or has been bundled for the browser (running in ${runtimeName}).
In case this error is unexpected for you, please report it in https://pris.ly/prisma-prisma-bug-report,
)}
/** Shorthand utilities for JSON filtering / Prisma.DbNull = objectEnumValues.instances.DbNull Prisma.JsonNull = objectEnumValues.instances.JsonNull Prisma.AnyNull = objectEnumValues.instances.AnyNull
Prisma.NullTypes = { DbNull: objectEnumValues.classes.DbNull, JsonNull: objectEnumValues.classes.JsonNull, AnyNull: objectEnumValues.classes.AnyNull }
/** Enums
Prisma
Source: my-backend/node_modules/.prisma/client/index.js
Signature: Prisma(.TransactionIsolationLevel = makeStrictEnum({
ReadUncommitted: 'ReadUncommitted',
ReadCommitted: 'ReadCommitted',
RepeatableRead: 'RepeatableRead',
Serializable: 'Serializable'
})
JSDoc:
Prisma Client JS version: 6.16.3 Query Engine version: bb420e667c1820a8c05a38023385f6cc7ef8e83a / Prisma.prismaVersion = { client: "6.16.3", engine: "bb420e667c1820a8c05a38023385f6cc7ef8e83a" }
Prisma.PrismaClientKnownRequestError = PrismaClientKnownRequestError; Prisma.PrismaClientUnknownRequestError = PrismaClientUnknownRequestError Prisma.PrismaClientRustPanicError = PrismaClientRustPanicError Prisma.PrismaClientInitializationError = PrismaClientInitializationError Prisma.PrismaClientValidationError = PrismaClientValidationError Prisma.Decimal = Decimal
/** Re-export of sql-template-tag / Prisma.sql = sqltag Prisma.empty = empty Prisma.join = join Prisma.raw = raw Prisma.validator = Public.validator
/** Extensions / Prisma.getExtensionContext = Extensions.getExtensionContext Prisma.defineExtension = Extensions.defineExtension
/** Shorthand utilities for JSON filtering / Prisma.DbNull = objectEnumValues.instances.DbNull Prisma.JsonNull = objectEnumValues.instances.JsonNull Prisma.AnyNull = objectEnumValues.instances.AnyNull
Prisma.NullTypes = { DbNull: objectEnumValues.classes.DbNull, JsonNull: objectEnumValues.classes.JsonNull, AnyNull: objectEnumValues.classes.AnyNull }
const path = require('path')
/** Enums
Prisma
Source: my-backend/node_modules/.prisma/client/wasm.js
Signature: Prisma(.TransactionIsolationLevel = makeStrictEnum({
ReadUncommitted: 'ReadUncommitted',
ReadCommitted: 'ReadCommitted',
RepeatableRead: 'RepeatableRead',
Serializable: 'Serializable'
})
JSDoc:
Prisma Client JS version: 6.16.3 Query Engine version: bb420e667c1820a8c05a38023385f6cc7ef8e83a / Prisma.prismaVersion = { client: "6.16.3", engine: "bb420e667c1820a8c05a38023385f6cc7ef8e83a" }
Prisma.PrismaClientKnownRequestError = PrismaClientKnownRequestError; Prisma.PrismaClientUnknownRequestError = PrismaClientUnknownRequestError Prisma.PrismaClientRustPanicError = PrismaClientRustPanicError Prisma.PrismaClientInitializationError = PrismaClientInitializationError Prisma.PrismaClientValidationError = PrismaClientValidationError Prisma.Decimal = Decimal
/** Re-export of sql-template-tag / Prisma.sql = sqltag Prisma.empty = empty Prisma.join = join Prisma.raw = raw Prisma.validator = Public.validator
/** Extensions / Prisma.getExtensionContext = Extensions.getExtensionContext Prisma.defineExtension = Extensions.defineExtension
/** Shorthand utilities for JSON filtering / Prisma.DbNull = objectEnumValues.instances.DbNull Prisma.JsonNull = objectEnumValues.instances.JsonNull Prisma.AnyNull = objectEnumValues.instances.AnyNull
Prisma.NullTypes = { DbNull: objectEnumValues.classes.DbNull, JsonNull: objectEnumValues.classes.JsonNull, AnyNull: objectEnumValues.classes.AnyNull }
/** Enums
formatArgs
Source: my-backend/node_modules/@babel/core/node_modules/debug/src/browser.js
Signature: formatArgs(= formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.storage = localstorage()
JSDoc:
This is the web browser implementation of debug().
colors
Source: my-backend/node_modules/@babel/core/node_modules/debug/src/browser.js
Signature: `colors(= [ '#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33' ];
/** * Currently only WebKit-based Web Inspectors, Firefox >= v31, * and the Firebug extension (any Firefox version)`
JSDoc:
Colors.
log
Source: my-backend/node_modules/@babel/core/node_modules/debug/src/browser.js
Signature: log(= console.debug || console.log || (()
JSDoc:
Colorize log arguments if enabled.
@api public /
function formatArgs(args) { args0 = (this.useColors ? '%c' : '') + this.namespace + (this.useColors ? ' %c' : ' ') + args0 + (this.useColors ? '%c ' : ' ') + '+' + module.exports.humanize(this.diff);
if (!this.useColors) {
return;
}
const c = 'color: ' + this.color;
args.splice(1, 0, c, 'color: inherit');
// The final "%c" is somewhat tricky, because there could be other
// arguments passed either before or after the %c, so we need to
// figure out the correct index to insert the CSS into
let index = 0;
let lastC = 0;
args[0].replace(/%[a-zA-Z%]/g, match => {
if (match === '%%') {
return;
}
index++;
if (match === '%c') {
// We only are interested in the *last* %c
// (the user may have provided their own)
lastC = index;
}
});
args.splice(lastC, 0, c);
}
/**
Invokes console.debug() when available.
No-op when console.debug is not a "function".
If console.debug is not available, falls back
to console.log.
@api public
init
Source: my-backend/node_modules/@babel/core/node_modules/debug/src/node.js
Signature: init(= init;
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.destroy = util.deprecate(
()
JSDoc:
Module dependencies. /
const tty = require('tty'); const util = require('util');
/**
This is the Node.js implementation of debug().
colors
Source: my-backend/node_modules/@babel/core/node_modules/debug/src/node.js
Signature: `colors(= [6, 2, 3, 4, 5, 1];
try { // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)`
JSDoc:
Colors.
inspectOpts
Source: my-backend/node_modules/@babel/core/node_modules/debug/src/node.js
Signature: inspectOpts(= Object.keys(process.env)
JSDoc:
Build up the default inspectOpts object from the environment variables.
$ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
formatArgs
Source: my-backend/node_modules/@babel/traverse/node_modules/debug/src/browser.js
Signature: formatArgs(= formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.storage = localstorage()
JSDoc:
This is the web browser implementation of debug().
colors
Source: my-backend/node_modules/@babel/traverse/node_modules/debug/src/browser.js
Signature: `colors(= [ '#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33' ];
/** * Currently only WebKit-based Web Inspectors, Firefox >= v31, * and the Firebug extension (any Firefox version)`
JSDoc:
Colors.
log
Source: my-backend/node_modules/@babel/traverse/node_modules/debug/src/browser.js
Signature: log(= console.debug || console.log || (()
JSDoc:
Colorize log arguments if enabled.
@api public /
function formatArgs(args) { args0 = (this.useColors ? '%c' : '') + this.namespace + (this.useColors ? ' %c' : ' ') + args0 + (this.useColors ? '%c ' : ' ') + '+' + module.exports.humanize(this.diff);
if (!this.useColors) {
return;
}
const c = 'color: ' + this.color;
args.splice(1, 0, c, 'color: inherit');
// The final "%c" is somewhat tricky, because there could be other
// arguments passed either before or after the %c, so we need to
// figure out the correct index to insert the CSS into
let index = 0;
let lastC = 0;
args[0].replace(/%[a-zA-Z%]/g, match => {
if (match === '%%') {
return;
}
index++;
if (match === '%c') {
// We only are interested in the *last* %c
// (the user may have provided their own)
lastC = index;
}
});
args.splice(lastC, 0, c);
}
/**
Invokes console.debug() when available.
No-op when console.debug is not a "function".
If console.debug is not available, falls back
to console.log.
@api public
init
Source: my-backend/node_modules/@babel/traverse/node_modules/debug/src/node.js
Signature: init(= init;
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.destroy = util.deprecate(
()
JSDoc:
Module dependencies. /
const tty = require('tty'); const util = require('util');
/**
This is the Node.js implementation of debug().
colors
Source: my-backend/node_modules/@babel/traverse/node_modules/debug/src/node.js
Signature: `colors(= [6, 2, 3, 4, 5, 1];
try { // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)`
JSDoc:
Colors.
inspectOpts
Source: my-backend/node_modules/@babel/traverse/node_modules/debug/src/node.js
Signature: inspectOpts(= Object.keys(process.env)
JSDoc:
Build up the default inspectOpts object from the environment variables.
$ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
isNumberLiteral
Source: my-backend/node_modules/@babel/types/lib/index-legacy.d.ts
Signature: isNumberLiteral(node: object | null | undefined, opts?: object | null)
JSDoc:
@deprecated Use NumericLiteral
/
export type NumberLiteral = NumericLiteral;
/**
@deprecated Use RegExpLiteral
/
export type RegexLiteral = RegExpLiteral;
/**
@deprecated Use RestElement
/
export type RestProperty = RestElement;
/**
@deprecated Use SpreadElement
/
export type SpreadProperty = SpreadElement;
export type Standardized = ArrayExpression | AssignmentExpression | BinaryExpression | InterpreterDirective | Directive | DirectiveLiteral | BlockStatement | BreakStatement | CallExpression | CatchClause | ConditionalExpression | ContinueStatement | DebuggerStatement | DoWhileStatement | EmptyStatement | ExpressionStatement | File | ForInStatement | ForStatement | FunctionDeclaration | FunctionExpression | Identifier | IfStatement | LabeledStatement | StringLiteral | NumericLiteral | NullLiteral | BooleanLiteral | RegExpLiteral | LogicalExpression | MemberExpression | NewExpression | Program | ObjectExpression | ObjectMethod | ObjectProperty | RestElement | ReturnStatement | SequenceExpression | ParenthesizedExpression | SwitchCase | SwitchStatement | ThisExpression | ThrowStatement | TryStatement | UnaryExpression | UpdateExpression | VariableDeclaration | VariableDeclarator | WhileStatement | WithStatement | AssignmentPattern | ArrayPattern | ArrowFunctionExpression | ClassBody | ClassExpression | ClassDeclaration | ExportAllDeclaration | ExportDefaultDeclaration | ExportNamedDeclaration | ExportSpecifier | ForOfStatement | ImportDeclaration | ImportDefaultSpecifier | ImportNamespaceSpecifier | ImportSpecifier | ImportExpression | MetaProperty | ClassMethod | ObjectPattern | SpreadElement | Super | TaggedTemplateExpression | TemplateElement | TemplateLiteral | YieldExpression | AwaitExpression | Import | BigIntLiteral | ExportNamespaceSpecifier | OptionalMemberExpression | OptionalCallExpression | ClassProperty | ClassAccessorProperty | ClassPrivateProperty | ClassPrivateMethod | PrivateName | StaticBlock | ImportAttribute; export type Expression = ArrayExpression | AssignmentExpression | BinaryExpression | CallExpression | ConditionalExpression | FunctionExpression | Identifier | StringLiteral | NumericLiteral | NullLiteral | BooleanLiteral | RegExpLiteral | LogicalExpression | MemberExpression | NewExpression | ObjectExpression | SequenceExpression | ParenthesizedExpression | ThisExpression | UnaryExpression | UpdateExpression | ArrowFunctionExpression | ClassExpression | ImportExpression | MetaProperty | Super | TaggedTemplateExpression | TemplateLiteral | YieldExpression | AwaitExpression | Import | BigIntLiteral | OptionalMemberExpression | OptionalCallExpression | TypeCastExpression | JSXElement | JSXFragment | BindExpression | DoExpression | RecordExpression | TupleExpression | DecimalLiteral | ModuleExpression | TopicReference | PipelineTopicExpression | PipelineBareFunction | PipelinePrimaryTopicReference | TSInstantiationExpression | TSAsExpression | TSSatisfiesExpression | TSTypeAssertion | TSNonNullExpression; export type Binary = BinaryExpression | LogicalExpression; export type Scopable = BlockStatement | CatchClause | DoWhileStatement | ForInStatement | ForStatement | FunctionDeclaration | FunctionExpression | Program | ObjectMethod | SwitchStatement | WhileStatement | ArrowFunctionExpression | ClassExpression | ClassDeclaration | ForOfStatement | ClassMethod | ClassPrivateMethod | StaticBlock | TSModuleBlock; export type BlockParent = BlockStatement | CatchClause | DoWhileStatement | ForInStatement | ForStatement | FunctionDeclaration | FunctionExpression | Program | ObjectMethod | SwitchStatement | WhileStatement | ArrowFunctionExpression | ForOfStatement | ClassMethod | ClassPrivateMethod | StaticBlock | TSModuleBlock; export type Block = BlockStatement | Program | TSModuleBlock; export type Statement = BlockStatement | BreakStatement | ContinueStatement | DebuggerStatement | DoWhileStatement | EmptyStatement | ExpressionStatement | ForInStatement | ForStatement | FunctionDeclaration | IfStatement | LabeledStatement | ReturnStatement | SwitchStatement | ThrowStatement | TryStatement | VariableDeclaration | WhileStatement | WithStatement | ClassDeclaration | ExportAllDeclaration | ExportDefaultDeclaration | ExportNamedDeclaration | ForOfStatement | ImportDeclaration | DeclareClass | DeclareFunction | DeclareInterface | DeclareModule | DeclareModuleExports | DeclareTypeAlias | DeclareOpaqueType | DeclareVariable | DeclareExportDeclaration | DeclareExportAllDeclaration | InterfaceDeclaration | OpaqueType | TypeAlias | EnumDeclaration | TSDeclareFunction | TSInterfaceDeclaration | TSTypeAliasDeclaration | TSEnumDeclaration | TSModuleDeclaration | TSImportEqualsDeclaration | TSExportAssignment | TSNamespaceExportDeclaration; export type Terminatorless = BreakStatement | ContinueStatement | ReturnStatement | ThrowStatement | YieldExpression | AwaitExpression; export type CompletionStatement = BreakStatement | ContinueStatement | ReturnStatement | ThrowStatement; export type Conditional = ConditionalExpression | IfStatement; export type Loop = DoWhileStatement | ForInStatement | ForStatement | WhileStatement | ForOfStatement; export type While = DoWhileStatement | WhileStatement; export type ExpressionWrapper = ExpressionStatement | ParenthesizedExpression | TypeCastExpression; export type For = ForInStatement | ForStatement | ForOfStatement; export type ForXStatement = ForInStatement | ForOfStatement; export type Function = FunctionDeclaration | FunctionExpression | ObjectMethod | ArrowFunctionExpression | ClassMethod | ClassPrivateMethod; export type FunctionParent = FunctionDeclaration | FunctionExpression | ObjectMethod | ArrowFunctionExpression | ClassMethod | ClassPrivateMethod | StaticBlock | TSModuleBlock; export type Pureish = FunctionDeclaration | FunctionExpression | StringLiteral | NumericLiteral | NullLiteral | BooleanLiteral | RegExpLiteral | ArrowFunctionExpression | BigIntLiteral | DecimalLiteral; export type Declaration = FunctionDeclaration | VariableDeclaration | ClassDeclaration | ExportAllDeclaration | ExportDefaultDeclaration | ExportNamedDeclaration | ImportDeclaration | DeclareClass | DeclareFunction | DeclareInterface | DeclareModule | DeclareModuleExports | DeclareTypeAlias | DeclareOpaqueType | DeclareVariable | DeclareExportDeclaration | DeclareExportAllDeclaration | InterfaceDeclaration | OpaqueType | TypeAlias | EnumDeclaration | TSDeclareFunction | TSInterfaceDeclaration | TSTypeAliasDeclaration | TSEnumDeclaration | TSModuleDeclaration | TSImportEqualsDeclaration; export type FunctionParameter = Identifier | RestElement | AssignmentPattern | ArrayPattern | ObjectPattern | VoidPattern; export type PatternLike = Identifier | MemberExpression | RestElement | AssignmentPattern | ArrayPattern | ObjectPattern | VoidPattern | TSAsExpression | TSSatisfiesExpression | TSTypeAssertion | TSNonNullExpression; export type LVal = Identifier | MemberExpression | RestElement | AssignmentPattern | ArrayPattern | ObjectPattern | TSParameterProperty | TSAsExpression | TSSatisfiesExpression | TSTypeAssertion | TSNonNullExpression; export type TSEntityName = Identifier | TSQualifiedName; export type Literal = StringLiteral | NumericLiteral | NullLiteral | BooleanLiteral | RegExpLiteral | TemplateLiteral | BigIntLiteral | DecimalLiteral; export type Immutable = StringLiteral | NumericLiteral | NullLiteral | BooleanLiteral | BigIntLiteral | JSXAttribute | JSXClosingElement | JSXElement | JSXExpressionContainer | JSXSpreadChild | JSXOpeningElement | JSXText | JSXFragment | JSXOpeningFragment | JSXClosingFragment | DecimalLiteral; export type UserWhitespacable = ObjectMethod | ObjectProperty | ObjectTypeInternalSlot | ObjectTypeCallProperty | ObjectTypeIndexer | ObjectTypeProperty | ObjectTypeSpreadProperty; export type Method = ObjectMethod | ClassMethod | ClassPrivateMethod; export type ObjectMember = ObjectMethod | ObjectProperty; export type Property = ObjectProperty | ClassProperty | ClassAccessorProperty | ClassPrivateProperty; export type UnaryLike = UnaryExpression | SpreadElement; export type Pattern = AssignmentPattern | ArrayPattern | ObjectPattern | VoidPattern; export type Class = ClassExpression | ClassDeclaration; export type ImportOrExportDeclaration = ExportAllDeclaration | ExportDefaultDeclaration | ExportNamedDeclaration | ImportDeclaration; export type ExportDeclaration = ExportAllDeclaration | ExportDefaultDeclaration | ExportNamedDeclaration; export type ModuleSpecifier = ExportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier | ImportSpecifier | ExportNamespaceSpecifier | ExportDefaultSpecifier; export type Accessor = ClassAccessorProperty; export type Private = ClassPrivateProperty | ClassPrivateMethod | PrivateName; export type Flow = AnyTypeAnnotation | ArrayTypeAnnotation | BooleanTypeAnnotation | BooleanLiteralTypeAnnotation | NullLiteralTypeAnnotation | ClassImplements | DeclareClass | DeclareFunction | DeclareInterface | DeclareModule | DeclareModuleExports | DeclareTypeAlias | DeclareOpaqueType | DeclareVariable | DeclareExportDeclaration | DeclareExportAllDeclaration | DeclaredPredicate | ExistsTypeAnnotation | FunctionTypeAnnotation | FunctionTypeParam | GenericTypeAnnotation | InferredPredicate | InterfaceExtends | InterfaceDeclaration | InterfaceTypeAnnotation | IntersectionTypeAnnotation | MixedTypeAnnotation | EmptyTypeAnnotation | NullableTypeAnnotation | NumberLiteralTypeAnnotation | NumberTypeAnnotation | ObjectTypeAnnotation | ObjectTypeInternalSlot | ObjectTypeCallProperty | ObjectTypeIndexer | ObjectTypeProperty | ObjectTypeSpreadProperty | OpaqueType | QualifiedTypeIdentifier | StringLiteralTypeAnnotation | StringTypeAnnotation | SymbolTypeAnnotation | ThisTypeAnnotation | TupleTypeAnnotation | TypeofTypeAnnotation | TypeAlias | TypeAnnotation | TypeCastExpression | TypeParameter | TypeParameterDeclaration | TypeParameterInstantiation | UnionTypeAnnotation | Variance | VoidTypeAnnotation | EnumDeclaration | EnumBooleanBody | EnumNumberBody | EnumStringBody | EnumSymbolBody | EnumBooleanMember | EnumNumberMember | EnumStringMember | EnumDefaultedMember | IndexedAccessType | OptionalIndexedAccessType; export type FlowType = AnyTypeAnnotation | ArrayTypeAnnotation | BooleanTypeAnnotation | BooleanLiteralTypeAnnotation | NullLiteralTypeAnnotation | ExistsTypeAnnotation | FunctionTypeAnnotation | GenericTypeAnnotation | InterfaceTypeAnnotation | IntersectionTypeAnnotation | MixedTypeAnnotation | EmptyTypeAnnotation | NullableTypeAnnotation | NumberLiteralTypeAnnotation | NumberTypeAnnotation | ObjectTypeAnnotation | StringLiteralTypeAnnotation | StringTypeAnnotation | SymbolTypeAnnotation | ThisTypeAnnotation | TupleTypeAnnotation | TypeofTypeAnnotation | UnionTypeAnnotation | VoidTypeAnnotation | IndexedAccessType | OptionalIndexedAccessType; export type FlowBaseAnnotation = AnyTypeAnnotation | BooleanTypeAnnotation | NullLiteralTypeAnnotation | MixedTypeAnnotation | EmptyTypeAnnotation | NumberTypeAnnotation | StringTypeAnnotation | SymbolTypeAnnotation | ThisTypeAnnotation | VoidTypeAnnotation; export type FlowDeclaration = DeclareClass | DeclareFunction | DeclareInterface | DeclareModule | DeclareModuleExports | DeclareTypeAlias | DeclareOpaqueType | DeclareVariable | DeclareExportDeclaration | DeclareExportAllDeclaration | InterfaceDeclaration | OpaqueType | TypeAlias; export type FlowPredicate = DeclaredPredicate | InferredPredicate; export type EnumBody = EnumBooleanBody | EnumNumberBody | EnumStringBody | EnumSymbolBody; export type EnumMember = EnumBooleanMember | EnumNumberMember | EnumStringMember | EnumDefaultedMember; export type JSX = JSXAttribute | JSXClosingElement | JSXElement | JSXEmptyExpression | JSXExpressionContainer | JSXSpreadChild | JSXIdentifier | JSXMemberExpression | JSXNamespacedName | JSXOpeningElement | JSXSpreadAttribute | JSXText | JSXFragment | JSXOpeningFragment | JSXClosingFragment; export type Miscellaneous = Noop | Placeholder | V8IntrinsicIdentifier; export type TypeScript = TSParameterProperty | TSDeclareFunction | TSDeclareMethod | TSQualifiedName | TSCallSignatureDeclaration | TSConstructSignatureDeclaration | TSPropertySignature | TSMethodSignature | TSIndexSignature | TSAnyKeyword | TSBooleanKeyword | TSBigIntKeyword | TSIntrinsicKeyword | TSNeverKeyword | TSNullKeyword | TSNumberKeyword | TSObjectKeyword | TSStringKeyword | TSSymbolKeyword | TSUndefinedKeyword | TSUnknownKeyword | TSVoidKeyword | TSThisType | TSFunctionType | TSConstructorType | TSTypeReference | TSTypePredicate | TSTypeQuery | TSTypeLiteral | TSArrayType | TSTupleType | TSOptionalType | TSRestType | TSNamedTupleMember | TSUnionType | TSIntersectionType | TSConditionalType | TSInferType | TSParenthesizedType | TSTypeOperator | TSIndexedAccessType | TSMappedType | TSTemplateLiteralType | TSLiteralType | TSExpressionWithTypeArguments | TSInterfaceDeclaration | TSInterfaceBody | TSTypeAliasDeclaration | TSInstantiationExpression | TSAsExpression | TSSatisfiesExpression | TSTypeAssertion | TSEnumBody | TSEnumDeclaration | TSEnumMember | TSModuleDeclaration | TSModuleBlock | TSImportType | TSImportEqualsDeclaration | TSExternalModuleReference | TSNonNullExpression | TSExportAssignment | TSNamespaceExportDeclaration | TSTypeAnnotation | TSTypeParameterInstantiation | TSTypeParameterDeclaration | TSTypeParameter; export type TSTypeElement = TSCallSignatureDeclaration | TSConstructSignatureDeclaration | TSPropertySignature | TSMethodSignature | TSIndexSignature; export type TSType = TSAnyKeyword | TSBooleanKeyword | TSBigIntKeyword | TSIntrinsicKeyword | TSNeverKeyword | TSNullKeyword | TSNumberKeyword | TSObjectKeyword | TSStringKeyword | TSSymbolKeyword | TSUndefinedKeyword | TSUnknownKeyword | TSVoidKeyword | TSThisType | TSFunctionType | TSConstructorType | TSTypeReference | TSTypePredicate | TSTypeQuery | TSTypeLiteral | TSArrayType | TSTupleType | TSOptionalType | TSRestType | TSUnionType | TSIntersectionType | TSConditionalType | TSInferType | TSParenthesizedType | TSTypeOperator | TSIndexedAccessType | TSMappedType | TSTemplateLiteralType | TSLiteralType | TSExpressionWithTypeArguments | TSImportType; export type TSBaseType = TSAnyKeyword | TSBooleanKeyword | TSBigIntKeyword | TSIntrinsicKeyword | TSNeverKeyword | TSNullKeyword | TSNumberKeyword | TSObjectKeyword | TSStringKeyword | TSSymbolKeyword | TSUndefinedKeyword | TSUnknownKeyword | TSVoidKeyword | TSThisType | TSTemplateLiteralType | TSLiteralType; export type ModuleDeclaration = ExportAllDeclaration | ExportDefaultDeclaration | ExportNamedDeclaration | ImportDeclaration;
export interface Aliases { Standardized: Standardized; Expression: Expression; Binary: Binary; Scopable: Scopable; BlockParent: BlockParent; Block: Block; Statement: Statement; Terminatorless: Terminatorless; CompletionStatement: CompletionStatement; Conditional: Conditional; Loop: Loop; While: While; ExpressionWrapper: ExpressionWrapper; For: For; ForXStatement: ForXStatement; Function: Function; FunctionParent: FunctionParent; Pureish: Pureish; Declaration: Declaration; FunctionParameter: FunctionParameter; PatternLike: PatternLike; LVal: LVal; TSEntityName: TSEntityName; Literal: Literal; Immutable: Immutable; UserWhitespacable: UserWhitespacable; Method: Method; ObjectMember: ObjectMember; Property: Property; UnaryLike: UnaryLike; Pattern: Pattern; Class: Class; ImportOrExportDeclaration: ImportOrExportDeclaration; ExportDeclaration: ExportDeclaration; ModuleSpecifier: ModuleSpecifier; Accessor: Accessor; Private: Private; Flow: Flow; FlowType: FlowType; FlowBaseAnnotation: FlowBaseAnnotation; FlowDeclaration: FlowDeclaration; FlowPredicate: FlowPredicate; EnumBody: EnumBody; EnumMember: EnumMember; JSX: JSX; Miscellaneous: Miscellaneous; TypeScript: TypeScript; TSTypeElement: TSTypeElement; TSType: TSType; TSBaseType: TSBaseType; ModuleDeclaration: ModuleDeclaration; }
export function arrayExpression(elements?: ArrayisNumericLiteral
assertNumberLiteral
Source: my-backend/node_modules/@babel/types/lib/index-legacy.d.ts
Signature: assertNumberLiteral(node: object | null | undefined, opts?: object | null)
JSDoc:
@deprecated Use assertNumericLiteral
isRegexLiteral
Source: my-backend/node_modules/@babel/types/lib/index-legacy.d.ts
Signature: isRegexLiteral(node: object | null | undefined, opts?: object | null)
JSDoc:
@deprecated Use isRegExpLiteral
assertRegexLiteral
Source: my-backend/node_modules/@babel/types/lib/index-legacy.d.ts
Signature: assertRegexLiteral(node: object | null | undefined, opts?: object | null)
JSDoc:
@deprecated Use assertRegExpLiteral
isRestProperty
Source: my-backend/node_modules/@babel/types/lib/index-legacy.d.ts
Signature: isRestProperty(node: object | null | undefined, opts?: object | null)
JSDoc:
@deprecated Use isRestElement
assertRestProperty
Source: my-backend/node_modules/@babel/types/lib/index-legacy.d.ts
Signature: assertRestProperty(node: object | null | undefined, opts?: object | null)
JSDoc:
@deprecated Use assertRestElement
isSpreadProperty
Source: my-backend/node_modules/@babel/types/lib/index-legacy.d.ts
Signature: isSpreadProperty(node: object | null | undefined, opts?: object | null)
JSDoc:
@deprecated Use isSpreadElement
assertSpreadProperty
Source: my-backend/node_modules/@babel/types/lib/index-legacy.d.ts
Signature: assertSpreadProperty(node: object | null | undefined, opts?: object | null)
JSDoc:
@deprecated Use assertSpreadElement
cloneProcessCov
Source: my-backend/node_modules/@bcoe/v8-coverage/dist/lib/_src/clone.ts
Signature: cloneProcessCov(processCov: Readonly<ProcessCov>)
JSDoc:
Creates a deep copy of a process coverage.
@param processCov Process coverage to clone. @return Cloned process coverage.
cloneScriptCov
Source: my-backend/node_modules/@bcoe/v8-coverage/dist/lib/_src/clone.ts
Signature: cloneScriptCov(scriptCov: Readonly<ScriptCov>)
JSDoc:
Creates a deep copy of a script coverage.
@param scriptCov Script coverage to clone. @return Cloned script coverage.
cloneFunctionCov
Source: my-backend/node_modules/@bcoe/v8-coverage/dist/lib/_src/clone.ts
Signature: cloneFunctionCov(functionCov: Readonly<FunctionCov>)
JSDoc:
Creates a deep copy of a function coverage.
@param functionCov Function coverage to clone. @return Cloned function coverage.
cloneRangeCov
Source: my-backend/node_modules/@bcoe/v8-coverage/dist/lib/_src/clone.ts
Signature: cloneRangeCov(rangeCov: Readonly<RangeCov>)
JSDoc:
Creates a deep copy of a function coverage.
@param rangeCov Range coverage to clone. @return Cloned range coverage.
compareScriptCovs
Source: my-backend/node_modules/@bcoe/v8-coverage/dist/lib/_src/compare.ts
Signature: compareScriptCovs(a: Readonly<ScriptCov>, b: Readonly<ScriptCov>)
JSDoc:
Compares two script coverages.
The result corresponds to the comparison of their url value (alphabetical sort).
compareFunctionCovs
Source: my-backend/node_modules/@bcoe/v8-coverage/dist/lib/_src/compare.ts
Signature: compareFunctionCovs(a: Readonly<FunctionCov>, b: Readonly<FunctionCov>)
JSDoc:
Compares two function coverages.
The result corresponds to the comparison of the root ranges.
compareRangeCovs
Source: my-backend/node_modules/@bcoe/v8-coverage/dist/lib/_src/compare.ts
Signature: compareRangeCovs(a: Readonly<RangeCov>, b: Readonly<RangeCov>)
JSDoc:
Compares two range coverages.
The ranges are first ordered by ascending startOffset and then by
descending endOffset.
This corresponds to a pre-order tree traversal.
mergeProcessCovs
Source: my-backend/node_modules/@bcoe/v8-coverage/dist/lib/_src/merge.ts
Signature: mergeProcessCovs(processCovs: ReadonlyArray<ProcessCov>)
JSDoc:
Merges a list of process coverages.
The result is normalized. The input values may be mutated, it is not safe to use them after passing them to this function. The computation is synchronous.
@param processCovs Process coverages to merge. @return Merged process coverage.
mergeScriptCovs
Source: my-backend/node_modules/@bcoe/v8-coverage/dist/lib/_src/merge.ts
Signature: mergeScriptCovs(scriptCovs: ReadonlyArray<ScriptCov>)
JSDoc:
Merges a list of matching script coverages.
Scripts are matching if they have the same url.
The result is normalized.
The input values may be mutated, it is not safe to use them after passing
them to this function.
The computation is synchronous.
@param scriptCovs Process coverages to merge.
@return Merged script coverage, or undefined if the input list was empty.
mergeFunctionCovs
Source: my-backend/node_modules/@bcoe/v8-coverage/dist/lib/_src/merge.ts
Signature: mergeFunctionCovs(funcCovs: ReadonlyArray<FunctionCov>)
JSDoc:
Returns a string representation of the root range of the function.
This string can be used to match function with same root range.
The string is derived from the start and end offsets of the root range of
the function.
This assumes that ranges is non-empty (true for valid function coverages).
@param funcCov Function coverage with the range to stringify
@internal
/
function stringifyFunctionRootRange(funcCov: Readonly${rootRange.startOffset.toString(10)};${rootRange.endOffset.toString(10)};
}
/** Merges a list of matching function coverages.
Functions are matching if their root ranges have the same span. The result is normalized. The input values may be mutated, it is not safe to use them after passing them to this function. The computation is synchronous.
@param funcCovs Function coverages to merge.
@return Merged function coverage, or undefined if the input list was empty.
normalizeProcessCov
Source: my-backend/node_modules/@bcoe/v8-coverage/dist/lib/_src/normalize.ts
Signature: normalizeProcessCov(processCov: ProcessCov)
JSDoc:
Normalizes a process coverage.
Sorts the scripts alphabetically by url.
Reassigns script ids: the script at index 0 receives "0", the script at
index 1 receives "1" etc.
This does not normalize the script coverages.
@param processCov Process coverage to normalize.
deepNormalizeProcessCov
Source: my-backend/node_modules/@bcoe/v8-coverage/dist/lib/_src/normalize.ts
Signature: deepNormalizeProcessCov(processCov: ProcessCov)
JSDoc:
Normalizes a process coverage deeply.
Normalizes the script coverages deeply, then normalizes the process coverage itself.
@param processCov Process coverage to normalize.
normalizeScriptCov
Source: my-backend/node_modules/@bcoe/v8-coverage/dist/lib/_src/normalize.ts
Signature: normalizeScriptCov(scriptCov: ScriptCov)
JSDoc:
Normalizes a script coverage.
Sorts the function by root range (pre-order sort). This does not normalize the function coverages.
@param scriptCov Script coverage to normalize.
deepNormalizeScriptCov
Source: my-backend/node_modules/@bcoe/v8-coverage/dist/lib/_src/normalize.ts
Signature: deepNormalizeScriptCov(scriptCov: ScriptCov)
JSDoc:
Normalizes a script coverage deeply.
Normalizes the function coverages deeply, then normalizes the script coverage itself.
@param scriptCov Script coverage to normalize.
normalizeFunctionCov
Source: my-backend/node_modules/@bcoe/v8-coverage/dist/lib/_src/normalize.ts
Signature: normalizeFunctionCov(funcCov: FunctionCov)
JSDoc:
Normalizes a function coverage.
Sorts the ranges (pre-order sort). TODO: Tree-based normalization of the ranges.
@param funcCov Function coverage to normalize.
normalizeRangeTree
Source: my-backend/node_modules/@bcoe/v8-coverage/dist/lib/_src/normalize.ts
Signature: normalizeRangeTree(tree: RangeTree)
JSDoc:
@internal
cloneProcessCov
Source: my-backend/node_modules/@bcoe/v8-coverage/src/lib/clone.ts
Signature: cloneProcessCov(processCov: Readonly<ProcessCov>)
JSDoc:
Creates a deep copy of a process coverage.
@param processCov Process coverage to clone. @return Cloned process coverage.
cloneScriptCov
Source: my-backend/node_modules/@bcoe/v8-coverage/src/lib/clone.ts
Signature: cloneScriptCov(scriptCov: Readonly<ScriptCov>)
JSDoc:
Creates a deep copy of a script coverage.
@param scriptCov Script coverage to clone. @return Cloned script coverage.
cloneFunctionCov
Source: my-backend/node_modules/@bcoe/v8-coverage/src/lib/clone.ts
Signature: cloneFunctionCov(functionCov: Readonly<FunctionCov>)
JSDoc:
Creates a deep copy of a function coverage.
@param functionCov Function coverage to clone. @return Cloned function coverage.
cloneRangeCov
Source: my-backend/node_modules/@bcoe/v8-coverage/src/lib/clone.ts
Signature: cloneRangeCov(rangeCov: Readonly<RangeCov>)
JSDoc:
Creates a deep copy of a function coverage.
@param rangeCov Range coverage to clone. @return Cloned range coverage.
compareScriptCovs
Source: my-backend/node_modules/@bcoe/v8-coverage/src/lib/compare.ts
Signature: compareScriptCovs(a: Readonly<ScriptCov>, b: Readonly<ScriptCov>)
JSDoc:
Compares two script coverages.
The result corresponds to the comparison of their url value (alphabetical sort).
compareFunctionCovs
Source: my-backend/node_modules/@bcoe/v8-coverage/src/lib/compare.ts
Signature: compareFunctionCovs(a: Readonly<FunctionCov>, b: Readonly<FunctionCov>)
JSDoc:
Compares two function coverages.
The result corresponds to the comparison of the root ranges.
compareRangeCovs
Source: my-backend/node_modules/@bcoe/v8-coverage/src/lib/compare.ts
Signature: compareRangeCovs(a: Readonly<RangeCov>, b: Readonly<RangeCov>)
JSDoc:
Compares two range coverages.
The ranges are first ordered by ascending startOffset and then by
descending endOffset.
This corresponds to a pre-order tree traversal.
mergeProcessCovs
Source: my-backend/node_modules/@bcoe/v8-coverage/src/lib/merge.ts
Signature: mergeProcessCovs(processCovs: ReadonlyArray<ProcessCov>)
JSDoc:
Merges a list of process coverages.
The result is normalized. The input values may be mutated, it is not safe to use them after passing them to this function. The computation is synchronous.
@param processCovs Process coverages to merge. @return Merged process coverage.
mergeScriptCovs
Source: my-backend/node_modules/@bcoe/v8-coverage/src/lib/merge.ts
Signature: mergeScriptCovs(scriptCovs: ReadonlyArray<ScriptCov>)
JSDoc:
Merges a list of matching script coverages.
Scripts are matching if they have the same url.
The result is normalized.
The input values may be mutated, it is not safe to use them after passing
them to this function.
The computation is synchronous.
@param scriptCovs Process coverages to merge.
@return Merged script coverage, or undefined if the input list was empty.
mergeFunctionCovs
Source: my-backend/node_modules/@bcoe/v8-coverage/src/lib/merge.ts
Signature: mergeFunctionCovs(funcCovs: ReadonlyArray<FunctionCov>)
JSDoc:
Returns a string representation of the root range of the function.
This string can be used to match function with same root range.
The string is derived from the start and end offsets of the root range of
the function.
This assumes that ranges is non-empty (true for valid function coverages).
@param funcCov Function coverage with the range to stringify
@internal
/
function stringifyFunctionRootRange(funcCov: Readonly${rootRange.startOffset.toString(10)};${rootRange.endOffset.toString(10)};
}
/** Merges a list of matching function coverages.
Functions are matching if their root ranges have the same span. The result is normalized. The input values may be mutated, it is not safe to use them after passing them to this function. The computation is synchronous.
@param funcCovs Function coverages to merge.
@return Merged function coverage, or undefined if the input list was empty.
normalizeProcessCov
Source: my-backend/node_modules/@bcoe/v8-coverage/src/lib/normalize.ts
Signature: normalizeProcessCov(processCov: ProcessCov)
JSDoc:
Normalizes a process coverage.
Sorts the scripts alphabetically by url.
Reassigns script ids: the script at index 0 receives "0", the script at
index 1 receives "1" etc.
This does not normalize the script coverages.
@param processCov Process coverage to normalize.
deepNormalizeProcessCov
Source: my-backend/node_modules/@bcoe/v8-coverage/src/lib/normalize.ts
Signature: deepNormalizeProcessCov(processCov: ProcessCov)
JSDoc:
Normalizes a process coverage deeply.
Normalizes the script coverages deeply, then normalizes the process coverage itself.
@param processCov Process coverage to normalize.
normalizeScriptCov
Source: my-backend/node_modules/@bcoe/v8-coverage/src/lib/normalize.ts
Signature: normalizeScriptCov(scriptCov: ScriptCov)
JSDoc:
Normalizes a script coverage.
Sorts the function by root range (pre-order sort). This does not normalize the function coverages.
@param scriptCov Script coverage to normalize.
deepNormalizeScriptCov
Source: my-backend/node_modules/@bcoe/v8-coverage/src/lib/normalize.ts
Signature: deepNormalizeScriptCov(scriptCov: ScriptCov)
JSDoc:
Normalizes a script coverage deeply.
Normalizes the function coverages deeply, then normalizes the script coverage itself.
@param scriptCov Script coverage to normalize.
normalizeFunctionCov
Source: my-backend/node_modules/@bcoe/v8-coverage/src/lib/normalize.ts
Signature: normalizeFunctionCov(funcCov: FunctionCov)
JSDoc:
Normalizes a function coverage.
Sorts the ranges (pre-order sort). TODO: Tree-based normalization of the ranges.
@param funcCov Function coverage to normalize.
normalizeRangeTree
Source: my-backend/node_modules/@bcoe/v8-coverage/src/lib/normalize.ts
Signature: normalizeRangeTree(tree: RangeTree)
JSDoc:
@internal
getPath
Source: my-backend/node_modules/@jest/expect-utils/build/utils.js
Signature: getPath(= getPath;
const getObjectSubset = (
object,
subset,
customTesters = [],
seenReferences = new WeakMap()
JSDoc:
Copyright (c) Meta Platforms, Inc. and affiliates.
This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree.
/
/**
Checks if hasOwnProperty(object, key) up the prototype chain, stopping at Object.prototype.
/
const hasPropertyInObject = (object, key) => {
const shouldTerminate =
!object || typeof object !== 'object' || object === Object.prototype;
if (shouldTerminate) {
return false;
}
return (
Object.prototype.hasOwnProperty.call(object, key) ||
hasPropertyInObject(Object.getPrototypeOf(object), key)
);
};
// Retrieves an object's keys for evaluation by getObjectSubset. This evaluates
// the prototype chain for string keys but not for symbols. (Otherwise, it
// could find values such as a Set or Map's Symbol.toStringTag, with unexpected
// results.)
const getObjectKeys = object => [
...Object.keys(object),
...Object.getOwnPropertySymbols(object)
];
exports.getObjectKeys = getObjectKeys;
const getPath = (object, propertyPath) => {
if (!Array.isArray(propertyPath)) {
propertyPath = pathAsArray(propertyPath);
}
if (propertyPath.length) {
const lastProp = propertyPath.length === 1;
const prop = propertyPath0;
const newObject = object[prop];
if (!lastProp && (newObject === null || newObject === undefined)) {
// This is not the last prop in the chain. If we keep recursing it will
// hit a can't access property X of undefined | null. At this point we
// know that the chain has broken and we can return right away.
return {
hasEndProp: false,
lastTraversedObject: object,
traversedPath: []
};
}
const result = getPath(newObject, propertyPath.slice(1));
if (result.lastTraversedObject === null) {
result.lastTraversedObject = object;
}
result.traversedPath.unshift(prop);
if (lastProp) {
// Does object have the property with an undefined value?
// Although primitive values support bracket notation (above)
// they would throw TypeError for in operator (below).
result.endPropIsDefined =
!(0, _jestGetType.isPrimitive)(object) && prop in object;
result.hasEndProp = newObject !== undefined || result.endPropIsDefined;
if (!result.hasEndProp) {
result.traversedPath.shift();
}
}
return result;
}
return {
lastTraversedObject: null,
traversedPath: [],
value: object
};
};
// Strip properties from object that are not present in the subset. Useful for // printing the diff for toMatchObject() without adding unrelated noise. /* eslint-disable @typescript-eslint/explicit-module-boundary-types
addSegment
Source: my-backend/node_modules/@jridgewell/gen-mapping/src/gen-mapping.ts
Signature: addSegment(
map: GenMapping,
genLine: number,
genColumn: number,
source?: null,
sourceLine?: null,
sourceColumn?: null,
name?: null,
content?: null,
)
JSDoc:
Provides the state to generate a sourcemap.
/
export class GenMapping {
declare private _names: SetArray
constructor({ file, sourceRoot }: Options = {}) { this._names = new SetArray(); this._sources = new SetArray(); this._sourcesContent = []; this._mappings = []; // this._originalScopes = []; // this._generatedRanges = []; this.file = file; this.sourceRoot = sourceRoot; this._ignoreList = new SetArray(); } }
interface PublicMap { _names: GenMapping['_names']; _sources: GenMapping['_sources']; _sourcesContent: GenMapping['_sourcesContent']; _mappings: GenMapping['_mappings']; // _originalScopes: GenMapping['_originalScopes']; // _generatedRanges: GenMapping['_generatedRanges']; _ignoreList: GenMapping['_ignoreList']; }
/** Typescript doesn't allow friend access to private fields, so this just casts the map into a type with public access modifiers. / function cast(map: unknown): PublicMap { return map as any; }
/**
A low-level API to associate a generated position with an original source position. Line and
column here are 0-based, unlike addMapping.
addMapping
Source: my-backend/node_modules/@jridgewell/gen-mapping/src/gen-mapping.ts
Signature: addMapping(
map: GenMapping,
mapping: {
generated: Pos;
source?: null;
original?: null;
name?: null;
content?: null;
},
)
JSDoc:
A high-level API to associate a generated position with an original source position. Line is
1-based, but column is 0-based, due to legacy behavior in source-map library.
setSourceContent
Source: my-backend/node_modules/@jridgewell/gen-mapping/src/gen-mapping.ts
Signature: setSourceContent(map: GenMapping, source: string, content: string | null)
JSDoc:
Same as addSegment, but will only add the segment if it generates useful information in the
resulting map. This only works correctly if segments are added in order, meaning you should
not add a segment with a lower generated line/column than one that came before.
/
export const maybeAddSegment: typeof addSegment = (
map,
genLine,
genColumn,
source,
sourceLine,
sourceColumn,
name,
content,
) => {
return addSegmentInternal(
true,
map,
genLine,
genColumn,
source,
sourceLine,
sourceColumn,
name,
content,
);
};
/
Same as addMapping, but will only add the mapping if it generates useful information in the
resulting map. This only works correctly if mappings are added in order**, meaning you should
not add a mapping with a lower generated line/column than one that came before.
/
export const maybeAddMapping: typeof addMapping = (map, mapping) => {
return addMappingInternal(true, map, mapping as Parameters
/** Adds/removes the content of the source file to the source map.
toDecodedMap
Source: my-backend/node_modules/@jridgewell/gen-mapping/src/gen-mapping.ts
Signature: toDecodedMap(map: GenMapping)
JSDoc:
Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects a sourcemap, or to JSON.stringify.
toEncodedMap
Source: my-backend/node_modules/@jridgewell/gen-mapping/src/gen-mapping.ts
Signature: toEncodedMap(map: GenMapping)
JSDoc:
Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects a sourcemap, or to JSON.stringify.
fromMap
Source: my-backend/node_modules/@jridgewell/gen-mapping/src/gen-mapping.ts
Signature: fromMap(input: SourceMapInput)
JSDoc:
Constructs a new GenMapping, using the already present mappings of the input.
allMappings
Source: my-backend/node_modules/@jridgewell/gen-mapping/src/gen-mapping.ts
Signature: allMappings(map: GenMapping)
JSDoc:
Returns an array of high-level mapping objects for every recorded segment, which could then be
passed to the source-map library.
get
Source: my-backend/node_modules/@jridgewell/gen-mapping/src/set-array.ts
Signature: get(<T extends Key>(setarr: SetArray<T>, key: T)
JSDoc:
SetArray acts like a Set (allowing only one occurrence of a string key), but provides the
index of the key in the backing array.
This is designed to allow synchronizing a second array with the contents of the backing array,
like how in a sourcemap sourcesContent[i] is the source content associated with source[i],
and there are never duplicates.
/
export class SetArray
constructor() { this._indexes = { proto: null } as any; this.array = []; } }
interface PublicSet
/**
Typescript doesn't allow friend access to private fields, so this just casts the set into a type
with public access modifiers.
/
function cast
/**
Gets the index associated with key in the backing array, if it is already present.
put
Source: my-backend/node_modules/@jridgewell/gen-mapping/src/set-array.ts
Signature: put(<T extends Key>(setarr: SetArray<T>, key: T)
JSDoc:
Puts key into the backing array, if it is not already present. Returns
the index of the key in the backing array.
pop
Source: my-backend/node_modules/@jridgewell/gen-mapping/src/set-array.ts
Signature: pop(<T extends Key>(setarr: SetArray<T>)
JSDoc:
Pops the last added item out of the SetArray.
remove
Source: my-backend/node_modules/@jridgewell/gen-mapping/src/set-array.ts
Signature: remove(<T extends Key>(setarr: SetArray<T>, key: T)
JSDoc:
Removes the key, if it exists in the set.
MapSource
Source: my-backend/node_modules/@jridgewell/remapping/src/source-map-tree.ts
Signature: MapSource(map: TraceMap, sources: Sources[])
JSDoc:
MapSource represents a single sourcemap, with the ability to trace mappings into its child nodes (which may themselves be SourceMapTrees).
OriginalSource
Source: my-backend/node_modules/@jridgewell/remapping/src/source-map-tree.ts
Signature: OriginalSource(
source: string,
content: string | null,
ignore: boolean,
)
JSDoc:
A "leaf" node in the sourcemap tree, representing an original, unmodified source file. Recursive
segment tracing ends at the OriginalSource.
traceMappings
Source: my-backend/node_modules/@jridgewell/remapping/src/source-map-tree.ts
Signature: traceMappings(tree: MapSource)
JSDoc:
traceMappings is only called on the root level SourceMapTree, and begins the process of resolving each mapping in terms of the original source files.
originalPositionFor
Source: my-backend/node_modules/@jridgewell/remapping/src/source-map-tree.ts
Signature: originalPositionFor(
source: Sources,
line: number,
column: number,
name: string,
)
JSDoc:
originalPositionFor is only called on children SourceMapTrees. It recurses down into its own child SourceMapTrees, until we find the original source map.
binarySearch
Source: my-backend/node_modules/@jridgewell/trace-mapping/src/binary-search.ts
Signature: binarySearch(
haystack: SourceMapSegment[] | ReverseSegment[],
needle: number,
low: number,
high: number,
)
JSDoc:
A binary search implementation that returns the index if a match is found. If no match is found, then the left-index (the index associated with the item that comes just before the desired index) is returned. To maintain proper sort order, a splice would happen at the next index:
const array = [1, 3];
const needle = 2;
const index = binarySearch(array, needle, (item, needle) => item - needle);
assert.equal(index, 0);
array.splice(index + 1, 0, needle);
assert.deepEqual(array, [1, 2, 3]);
memoizedBinarySearch
Source: my-backend/node_modules/@jridgewell/trace-mapping/src/binary-search.ts
Signature: memoizedBinarySearch(
haystack: SourceMapSegment[] | ReverseSegment[],
needle: number,
state: MemoState,
key: number,
)
JSDoc:
This overly complicated beast is just to record the last tested line/column and the resulting index, allowing us to skip a few tests if mappings are monotonically increasing.
encodedMappings
Source: my-backend/node_modules/@jridgewell/trace-mapping/src/trace-mapping.ts
Signature: encodedMappings(map: TraceMap)
JSDoc:
Typescript doesn't allow friend access to private fields, so this just casts the map into a type with public access modifiers. / function cast(map: unknown): PublicMap { return map as any; }
/** Returns the encoded (VLQ string) form of the SourceMap's mappings field.
decodedMappings
Source: my-backend/node_modules/@jridgewell/trace-mapping/src/trace-mapping.ts
Signature: decodedMappings(map: TraceMap)
JSDoc:
Returns the decoded (array of lines of segments) form of the SourceMap's mappings field.
traceSegment
Source: my-backend/node_modules/@jridgewell/trace-mapping/src/trace-mapping.ts
Signature: traceSegment(
map: TraceMap,
line: number,
column: number,
)
JSDoc:
A low-level API to find the segment associated with a generated line/column (think, from a
stack trace). Line and column here are 0-based, unlike originalPositionFor.
originalPositionFor
Source: my-backend/node_modules/@jridgewell/trace-mapping/src/trace-mapping.ts
Signature: originalPositionFor(
map: TraceMap,
needle: Needle,
)
JSDoc:
A higher-level API to find the source/line/column associated with a generated line/column
(think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in
source-map library.
generatedPositionFor
Source: my-backend/node_modules/@jridgewell/trace-mapping/src/trace-mapping.ts
Signature: generatedPositionFor(
map: TraceMap,
needle: SourceNeedle,
)
JSDoc:
Finds the generated line/column position of the provided source/line/column source position.
allGeneratedPositionsFor
Source: my-backend/node_modules/@jridgewell/trace-mapping/src/trace-mapping.ts
Signature: allGeneratedPositionsFor(map: TraceMap, needle: SourceNeedle)
JSDoc:
Finds all generated line/column positions of the provided source/line/column source position.
eachMapping
Source: my-backend/node_modules/@jridgewell/trace-mapping/src/trace-mapping.ts
Signature: eachMapping(map: TraceMap, cb: (mapping: EachMapping)
JSDoc:
Iterates each mapping in generated position order.
sourceContentFor
Source: my-backend/node_modules/@jridgewell/trace-mapping/src/trace-mapping.ts
Signature: sourceContentFor(map: TraceMap, source: string)
JSDoc:
Retrieves the source content for a particular source, if its found. Returns null if not.
isIgnored
Source: my-backend/node_modules/@jridgewell/trace-mapping/src/trace-mapping.ts
Signature: isIgnored(map: TraceMap, source: string)
JSDoc:
Determines if the source is marked to ignore by the source map.
presortedDecodedMap
Source: my-backend/node_modules/@jridgewell/trace-mapping/src/trace-mapping.ts
Signature: presortedDecodedMap(map: DecodedSourceMap, mapUrl?: string)
JSDoc:
A helper that skips sorting of the input map's mappings array, which can be expensive for larger maps.
decodedMap
Source: my-backend/node_modules/@jridgewell/trace-mapping/src/trace-mapping.ts
Signature: decodedMap(
map: TraceMap,
)
JSDoc:
Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects a sourcemap, or to JSON.stringify.
encodedMap
Source: my-backend/node_modules/@jridgewell/trace-mapping/src/trace-mapping.ts
Signature: encodedMap(map: TraceMap)
JSDoc:
Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects a sourcemap, or to JSON.stringify.
abytes
Source: my-backend/node_modules/@noble/hashes/_assert.js
Signature: abytes(= utils_ts_1.abytes;
/** @deprecated Use import fromnoble/hashes/utilsmodule */
exports.aexists = utils_ts_1.aexists;
/** @deprecated Use import fromnoble/hashes/utilsmodule */
exports.anumber = utils_ts_1.anumber;
/** @deprecated Use import fromnoble/hashes/utilsmodule */
exports.aoutput = utils_ts_1.aoutput;
//# sourceMappingURL=_assert.js.map)
JSDoc:
Internal assertion helpers.
@module
@deprecated
/
const utils_ts_1 = require("./utils.js");
/** @deprecated Use import from noble/hashes/utils module
SHA256_IV
Source: my-backend/node_modules/@noble/hashes/_md.js
Signature: SHA256_IV(= Uint32Array.from([
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
])
JSDoc:
Internal Merkle-Damgard hash utils.
@module
/
const utils_ts_1 = require("./utils.js");
/ Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */
function setBigUint64(view, byteOffset, value, isLE) {
if (typeof view.setBigUint64 === 'function')
return view.setBigUint64(byteOffset, value, isLE);
const _32n = BigInt(32);
const _u32_max = BigInt(0xffffffff);
const wh = Number((value >> _32n) & _u32_max);
const wl = Number(value & _u32_max);
const h = isLE ? 4 : 0;
const l = isLE ? 0 : 4;
view.setUint32(byteOffset + h, wh, isLE);
view.setUint32(byteOffset + l, wl, isLE);
}
/ Choice: a ? b : c /
function Chi(a, b, c) {
return (a & b) ^ (~a & c);
}
/ Majority function, true if any two inputs is true. /
function Maj(a, b, c) {
return (a & b) ^ (a & c) ^ (b & c);
}
/
Merkle-Damgard hash construction base class.
Could be used to create MD5, RIPEMD, SHA1, SHA2.
/
class HashMD extends utils_ts_1.Hash {
constructor(blockLen, outputLen, padOffset, isLE) {
super();
this.finished = false;
this.length = 0;
this.pos = 0;
this.destroyed = false;
this.blockLen = blockLen;
this.outputLen = outputLen;
this.padOffset = padOffset;
this.isLE = isLE;
this.buffer = new Uint8Array(blockLen);
this.view = (0, utils_ts_1.createView)(this.buffer);
}
update(data) {
(0, utils_ts_1.aexists)(this);
data = (0, utils_ts_1.toBytes)(data);
(0, utils_ts_1.abytes)(data);
const { view, buffer, blockLen } = this;
const len = data.length;
for (let pos = 0; pos < len;) {
const take = Math.min(blockLen - this.pos, len - pos);
// Fast path: we have at least one block in input, cast it to view and process
if (take === blockLen) {
const dataView = (0, utils_ts_1.createView)(data);
for (; blockLen <= len - pos; pos += blockLen)
this.process(dataView, pos);
continue;
}
buffer.set(data.subarray(pos, pos + take), this.pos);
this.pos += take;
pos += take;
if (this.pos === blockLen) {
this.process(view, 0);
this.pos = 0;
}
}
this.length += data.length;
this.roundClean();
return this;
}
digestInto(out) {
(0, utils_ts_1.aexists)(this);
(0, utils_ts_1.aoutput)(out, this);
this.finished = true;
// Padding
// We can avoid allocation of buffer for padding completely if it
// was previously not allocated here. But it won't change performance.
const { buffer, view, blockLen, isLE } = this;
let { pos } = this;
// append the bit '1' to the message
buffer[pos++] = 0b10000000;
(0, utils_ts_1.clean)(this.buffer.subarray(pos));
// we have less than padOffset left in buffer, so we cannot put length in
// current block, need process it and pad again
if (this.padOffset > blockLen - pos) {
this.process(view, 0);
pos = 0;
}
// Pad until full block byte with zeros
for (let i = pos; i < blockLen; i++)
buffer[i] = 0;
// Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that
// You need to write around 2 exabytes (u64_max / 8 / (10246)) for this to happen.
// So we just write lowest 64 bits of that value.
setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
this.process(view, 0);
const oview = (0, utils_ts_1.createView)(out);
const len = this.outputLen;
// NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT
if (len % 4)
throw new Error('_sha2: outputLen should be aligned to 32bit');
const outLen = len / 4;
const state = this.get();
if (outLen > state.length)
throw new Error('_sha2: outputLen bigger than state');
for (let i = 0; i < outLen; i++)
oview.setUint32(4 * i, state[i], isLE);
}
digest() {
const { buffer, outputLen } = this;
this.digestInto(buffer);
const res = buffer.slice(0, outputLen);
this.destroy();
return res;
}
_cloneInto(to) {
to || (to = new this.constructor());
to.set(...this.get());
const { blockLen, buffer, length, finished, destroyed, pos } = this;
to.destroyed = destroyed;
to.finished = finished;
to.length = length;
to.pos = pos;
if (length % blockLen)
to.buffer.set(buffer);
return to;
}
clone() {
return this._cloneInto();
}
}
exports.HashMD = HashMD;
/
Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.
Check out test/misc/sha2-gen-iv.js for recomputation guide.
/
/ Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19
SHA224_IV
Source: my-backend/node_modules/@noble/hashes/_md.js
Signature: SHA224_IV(= Uint32Array.from([
0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,
])
JSDoc:
Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53
SHA384_IV
Source: my-backend/node_modules/@noble/hashes/_md.js
Signature: SHA384_IV(= Uint32Array.from([
0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,
0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,
])
JSDoc:
Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53
SHA512_IV
Source: my-backend/node_modules/@noble/hashes/_md.js
Signature: SHA512_IV(= Uint32Array.from([
0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,
0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,
])
JSDoc:
Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19
blake224
Source: my-backend/node_modules/@noble/hashes/blake1.js
Signature: blake224(= (0, utils_ts_1.createOptHasher)
JSDoc:
Blake1 legacy hash function, one of SHA3 proposals. Rarely used. Check out blake2 or blake3 instead. https://www.aumasson.jp/blake/blake.pdf
In the best case, there are 0 allocations.
Differences from blake2:
- BE instead of LE
- Paddings, similar to MD5, RIPEMD, SHA1, SHA2, but:
- length flag is located before actual length
- padding block is compressed differently (no lengths)
Instead of msg[sigma[k]], we have
msg[sigma[k]] ^ constants[sigma[k-1]](-1 for g1, g2 without -1)
- Salt is XOR-ed into constants instead of state
- Salt is XOR-ed with output in
compress - Additional rows (+64 bytes) in SIGMA for new rounds
- Different round count:
- 14 / 10 rounds in blake256 / blake2s
- 16 / 12 rounds in blake512 / blake2b
- blake512: G1b: rotr 24 -> 25, G2b: rotr 63 -> 11 @module / const _blake_ts_1 = require("./_blake.js"); const _md_ts_1 = require("./_md.js"); const u64 = require("./_u64.js"); // prettier-ignore const utils_ts_1 = require("./utils.js"); // Empty zero-filled salt const EMPTY_SALT = / @PURE / new Uint32Array(8); class BLAKE1 extends utils_ts_1.Hash { constructor(blockLen, outputLen, lengthFlag, counterLen, saltLen, constants, opts = {}) { super(); this.finished = false; this.length = 0; this.pos = 0; this.destroyed = false; const { salt } = opts; this.blockLen = blockLen; this.outputLen = outputLen; this.lengthFlag = lengthFlag; this.counterLen = counterLen; this.buffer = new Uint8Array(blockLen); this.view = (0, utils_ts_1.createView)(this.buffer); if (salt) { let slt = salt; slt = (0, utils_ts_1.toBytes)(slt); (0, utils_ts_1.abytes)(slt); if (slt.length !== 4 * saltLen) throw new Error('wrong salt length'); const salt32 = (this.salt = new Uint32Array(saltLen)); const sv = (0, utils_ts_1.createView)(slt); this.constants = constants.slice(); for (let i = 0, offset = 0; i < salt32.length; i++, offset += 4) { salt32[i] = sv.getUint32(offset, false); this.constants[i] ^= salt32[i]; } } else { this.salt = EMPTY_SALT; this.constants = constants; } } update(data) { (0, utils_ts_1.aexists)(this); data = (0, utils_ts_1.toBytes)(data); (0, utils_ts_1.abytes)(data); // From _md, but update length before each compress const { view, buffer, blockLen } = this; const len = data.length; let dataView; for (let pos = 0; pos < len;) { const take = Math.min(blockLen - this.pos, len - pos); // Fast path: we have at least one block in input, cast it to view and process if (take === blockLen) { if (!dataView) dataView = (0, utils_ts_1.createView)(data); for (; blockLen <= len - pos; pos += blockLen) { this.length += blockLen; this.compress(dataView, pos); } continue; } buffer.set(data.subarray(pos, pos + take), this.pos); this.pos += take; pos += take; if (this.pos === blockLen) { this.length += blockLen; this.compress(view, 0, true); this.pos = 0; } } return this; } destroy() { this.destroyed = true; if (this.salt !== EMPTY_SALT) { (0, utils_ts_1.clean)(this.salt, this.constants); } } _cloneInto(to) { to || (to = new this.constructor()); to.set(...this.get()); const { buffer, length, finished, destroyed, constants, salt, pos } = this; to.buffer.set(buffer); to.constants = constants.slice(); to.destroyed = destroyed; to.finished = finished; to.length = length; to.pos = pos; to.salt = salt.slice(); return to; } clone() { return this._cloneInto(); } digestInto(out) { (0, utils_ts_1.aexists)(this); (0, utils_ts_1.aoutput)(out, this); this.finished = true; // Padding const { buffer, blockLen, counterLen, lengthFlag, view } = this; (0, utils_ts_1.clean)(buffer.subarray(this.pos)); // clean buf const counter = BigInt((this.length + this.pos) * 8); const counterPos = blockLen - counterLen - 1; buffer[this.pos] |= 128; // End block flag this.length += this.pos; // add unwritten length // Not enough in buffer for length: write what we have. if (this.pos > counterPos) { this.compress(view, 0); (0, utils_ts_1.clean)(buffer); this.pos = 0; } // Difference with md: here we have lengthFlag! buffer[counterPos] |= lengthFlag; // Length flag // We always set 8 byte length flag. Because length will overflow significantly sooner. (0, _md_ts_1.setBigUint64)(view, blockLen - 8, counter, false); this.compress(view, 0, this.pos !== 0); // don't add length if length is not empty block? // Write output (0, utils_ts_1.clean)(buffer); const v = (0, utils_ts_1.createView)(out); const state = this.get(); for (let i = 0; i < this.outputLen / 4; ++i) v.setUint32(i * 4, state[i]); } digest() { const { buffer, outputLen } = this; this.digestInto(buffer); const res = buffer.slice(0, outputLen); this.destroy(); return res; } } // Constants const B64C = / @PURE / Uint32Array.from([ 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b, 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, ]); // first half of C512 const B32C = B64C.slice(0, 16); const B256_IV = _md_ts_1.SHA256_IV.slice(); const B224_IV = _md_ts_1.SHA224_IV.slice(); const B384_IV = _md_ts_1.SHA384_IV.slice(); const B512_IV = _md_ts_1.SHA512_IV.slice(); function generateTBL256() { const TBL = []; for (let i = 0, j = 0; i < 14; i++, j += 16) { for (let offset = 1; offset < 16; offset += 2) { TBL.push(B32C[_blake_ts_1.BSIGMA[j + offset]]); TBL.push(B32C[_blake_ts_1.BSIGMA[j + offset - 1]]); } } return new Uint32Array(TBL); } const TBL256 = / @PURE / generateTBL256(); // C256[SIGMA[X]] precompute // Reusable temporary buffer const BLAKE256_W = / @PURE / new Uint32Array(16); class Blake1_32 extends BLAKE1 { constructor(outputLen, IV, lengthFlag, opts = {}) { super(64, outputLen, lengthFlag, 8, 4, B32C, opts); this.v0 = IV0 | 0; this.v1 = IV[1] | 0; this.v2 = IV[2] | 0; this.v3 = IV[3] | 0; this.v4 = IV[4] | 0; this.v5 = IV[5] | 0; this.v6 = IV[6] | 0; this.v7 = IV[7] | 0; } get() { const { v0, v1, v2, v3, v4, v5, v6, v7 } = this; return [v0, v1, v2, v3, v4, v5, v6, v7]; } // prettier-ignore set(v0, v1, v2, v3, v4, v5, v6, v7) { this.v0 = v0 | 0; this.v1 = v1 | 0; this.v2 = v2 | 0; this.v3 = v3 | 0; this.v4 = v4 | 0; this.v5 = v5 | 0; this.v6 = v6 | 0; this.v7 = v7 | 0; } destroy() { super.destroy(); this.set(0, 0, 0, 0, 0, 0, 0, 0); } compress(view, offset, withLength = true) { for (let i = 0; i < 16; i++, offset += 4) BLAKE256_W[i] = view.getUint32(offset, false); // NOTE: we cannot re-use compress from blake2s, since there is additional xor over u256[SIGMA[e]] let v00 = this.v0 | 0; let v01 = this.v1 | 0; let v02 = this.v2 | 0; let v03 = this.v3 | 0; let v04 = this.v4 | 0; let v05 = this.v5 | 0; let v06 = this.v6 | 0; let v07 = this.v7 | 0; let v08 = this.constants0 | 0; let v09 = this.constants[1] | 0; let v10 = this.constants[2] | 0; let v11 = this.constants[3] | 0; const { h, l } = u64.fromBig(BigInt(withLength ? this.length * 8 : 0)); let v12 = (this.constants[4] ^ l) >>> 0; let v13 = (this.constants[5] ^ l) >>> 0; let v14 = (this.constants[6] ^ h) >>> 0; let v15 = (this.constants[7] ^ h) >>> 0; // prettier-ignore for (let i = 0, k = 0, j = 0; i < 14; i++) { ({ a: v00, b: v04, c: v08, d: v12 } = (0, _blake_ts_1.G1s)(v00, v04, v08, v12, BLAKE256_W[_blake_ts_1.BSIGMA[k++]] ^ TBL256[j++])); ({ a: v00, b: v04, c: v08, d: v12 } = (0, _blake_ts_1.G2s)(v00, v04, v08, v12, BLAKE256_W[_blake_ts_1.BSIGMA[k++]] ^ TBL256[j++])); ({ a: v01, b: v05, c: v09, d: v13 } = (0, _blake_ts_1.G1s)(v01, v05, v09, v13, BLAKE256_W[_blake_ts_1.BSIGMA[k++]] ^ TBL256[j++])); ({ a: v01, b: v05, c: v09, d: v13 } = (0, _blake_ts_1.G2s)(v01, v05, v09, v13, BLAKE256_W[_blake_ts_1.BSIGMA[k++]] ^ TBL256[j++])); ({ a: v02, b: v06, c: v10, d: v14 } = (0, _blake_ts_1.G1s)(v02, v06, v10, v14, BLAKE256_W[_blake_ts_1.BSIGMA[k++]] ^ TBL256[j++])); ({ a: v02, b: v06, c: v10, d: v14 } = (0, _blake_ts_1.G2s)(v02, v06, v10, v14, BLAKE256_W[_blake_ts_1.BSIGMA[k++]] ^ TBL256[j++])); ({ a: v03, b: v07, c: v11, d: v15 } = (0, _blake_ts_1.G1s)(v03, v07, v11, v15, BLAKE256_W[_blake_ts_1.BSIGMA[k++]] ^ TBL256[j++])); ({ a: v03, b: v07, c: v11, d: v15 } = (0, _blake_ts_1.G2s)(v03, v07, v11, v15, BLAKE256_W[_blake_ts_1.BSIGMA[k++]] ^ TBL256[j++])); ({ a: v00, b: v05, c: v10, d: v15 } = (0, _blake_ts_1.G1s)(v00, v05, v10, v15, BLAKE256_W[_blake_ts_1.BSIGMA[k++]] ^ TBL256[j++])); ({ a: v00, b: v05, c: v10, d: v15 } = (0, _blake_ts_1.G2s)(v00, v05, v10, v15, BLAKE256_W[_blake_ts_1.BSIGMA[k++]] ^ TBL256[j++])); ({ a: v01, b: v06, c: v11, d: v12 } = (0, _blake_ts_1.G1s)(v01, v06, v11, v12, BLAKE256_W[_blake_ts_1.BSIGMA[k++]] ^ TBL256[j++])); ({ a: v01, b: v06, c: v11, d: v12 } = (0, _blake_ts_1.G2s)(v01, v06, v11, v12, BLAKE256_W[_blake_ts_1.BSIGMA[k++]] ^ TBL256[j++])); ({ a: v02, b: v07, c: v08, d: v13 } = (0, _blake_ts_1.G1s)(v02, v07, v08, v13, BLAKE256_W[_blake_ts_1.BSIGMA[k++]] ^ TBL256[j++])); ({ a: v02, b: v07, c: v08, d: v13 } = (0, _blake_ts_1.G2s)(v02, v07, v08, v13, BLAKE256_W[_blake_ts_1.BSIGMA[k++]] ^ TBL256[j++])); ({ a: v03, b: v04, c: v09, d: v14 } = (0, _blake_ts_1.G1s)(v03, v04, v09, v14, BLAKE256_W[_blake_ts_1.BSIGMA[k++]] ^ TBL256[j++])); ({ a: v03, b: v04, c: v09, d: v14 } = (0, _blake_ts_1.G2s)(v03, v04, v09, v14, BLAKE256_W[_blake_ts_1.BSIGMA[k++]] ^ TBL256[j++])); } this.v0 = (this.v0 ^ v00 ^ v08 ^ this.salt0) >>> 0; this.v1 = (this.v1 ^ v01 ^ v09 ^ this.salt[1]) >>> 0; this.v2 = (this.v2 ^ v02 ^ v10 ^ this.salt[2]) >>> 0; this.v3 = (this.v3 ^ v03 ^ v11 ^ this.salt[3]) >>> 0; this.v4 = (this.v4 ^ v04 ^ v12 ^ this.salt0) >>> 0; this.v5 = (this.v5 ^ v05 ^ v13 ^ this.salt[1]) >>> 0; this.v6 = (this.v6 ^ v06 ^ v14 ^ this.salt[2]) >>> 0; this.v7 = (this.v7 ^ v07 ^ v15 ^ this.salt[3]) >>> 0; (0, utils_ts_1.clean)(BLAKE256_W); } } const BBUF = / @PURE / new Uint32Array(32); const BLAKE512_W = / @PURE / new Uint32Array(32); function generateTBL512() { const TBL = []; for (let r = 0, k = 0; r < 16; r++, k += 16) { for (let offset = 1; offset < 16; offset += 2) { TBL.push(B64C[_blake_ts_1.BSIGMA[k + offset] * 2 + 0]); TBL.push(B64C[_blake_ts_1.BSIGMA[k + offset] * 2 + 1]); TBL.push(B64C[_blake_ts_1.BSIGMA[k + offset - 1] * 2 + 0]); TBL.push(B64C[_blake_ts_1.BSIGMA[k + offset - 1] * 2 + 1]); } } return new Uint32Array(TBL); } const TBL512 = / @PURE / generateTBL512(); // C512[SIGMA[X]] precompute // Mixing function G splitted in two halfs function G1b(a, b, c, d, msg, k) { const Xpos = 2 * _blake_ts_1.BSIGMA[k]; const Xl = msg[Xpos + 1] ^ TBL512[k * 2 + 1], Xh = msg[Xpos] ^ TBL512[k * 2]; // prettier-ignore let Al = BBUF[2 * a + 1], Ah = BBUF[2 * a]; // prettier-ignore let Bl = BBUF[2 * b + 1], Bh = BBUF[2 * b]; // prettier-ignore let Cl = BBUF[2 * c + 1], Ch = BBUF[2 * c]; // prettier-ignore let Dl = BBUF[2 * d + 1], Dh = BBUF[2 * d]; // prettier-ignore // v[a] = (v[a] + v[b] + x) | 0; let ll = u64.add3L(Al, Bl, Xl); Ah = u64.add3H(ll, Ah, Bh, Xh) >>> 0; Al = (ll | 0) >>> 0; // v[d] = rotr(v[d] ^ v[a], 32) ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); ({ Dh, Dl } = { Dh: u64.rotr32H(Dh, Dl), Dl: u64.rotr32L(Dh, Dl) }); // v[c] = (v[c] + v[d]) | 0; ({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl)); // v[b] = rotr(v[b] ^ v[c], 25) ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); ({ Bh, Bl } = { Bh: u64.rotrSH(Bh, Bl, 25), Bl: u64.rotrSL(Bh, Bl, 25) }); (BBUF[2 * a + 1] = Al), (BBUF[2 * a] = Ah); (BBUF[2 * b + 1] = Bl), (BBUF[2 * b] = Bh); (BBUF[2 * c + 1] = Cl), (BBUF[2 * c] = Ch); (BBUF[2 * d + 1] = Dl), (BBUF[2 * d] = Dh); } function G2b(a, b, c, d, msg, k) { const Xpos = 2 * _blake_ts_1.BSIGMA[k]; const Xl = msg[Xpos + 1] ^ TBL512[k * 2 + 1], Xh = msg[Xpos] ^ TBL512[k * 2]; // prettier-ignore let Al = BBUF[2 * a + 1], Ah = BBUF[2 * a]; // prettier-ignore let Bl = BBUF[2 * b + 1], Bh = BBUF[2 * b]; // prettier-ignore let Cl = BBUF[2 * c + 1], Ch = BBUF[2 * c]; // prettier-ignore let Dl = BBUF[2 * d + 1], Dh = BBUF[2 * d]; // prettier-ignore // v[a] = (v[a] + v[b] + x) | 0; let ll = u64.add3L(Al, Bl, Xl); Ah = u64.add3H(ll, Ah, Bh, Xh); Al = ll | 0; // v[d] = rotr(v[d] ^ v[a], 16) ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); ({ Dh, Dl } = { Dh: u64.rotrSH(Dh, Dl, 16), Dl: u64.rotrSL(Dh, Dl, 16) }); // v[c] = (v[c] + v[d]) | 0; ({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl)); // v[b] = rotr(v[b] ^ v[c], 11) ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); ({ Bh, Bl } = { Bh: u64.rotrSH(Bh, Bl, 11), Bl: u64.rotrSL(Bh, Bl, 11) }); (BBUF[2 * a + 1] = Al), (BBUF[2 * a] = Ah); (BBUF[2 * b + 1] = Bl), (BBUF[2 * b] = Bh); (BBUF[2 * c + 1] = Cl), (BBUF[2 * c] = Ch); (BBUF[2 * d + 1] = Dl), (BBUF[2 * d] = Dh); } class Blake1_64 extends BLAKE1 { constructor(outputLen, IV, lengthFlag, opts = {}) { super(128, outputLen, lengthFlag, 16, 8, B64C, opts); this.v0l = IV0 | 0; this.v0h = IV[1] | 0; this.v1l = IV[2] | 0; this.v1h = IV[3] | 0; this.v2l = IV[4] | 0; this.v2h = IV[5] | 0; this.v3l = IV[6] | 0; this.v3h = IV[7] | 0; this.v4l = IV[8] | 0; this.v4h = IV[9] | 0; this.v5l = IV[10] | 0; this.v5h = IV[11] | 0; this.v6l = IV[12] | 0; this.v6h = IV[13] | 0; this.v7l = IV[14] | 0; this.v7h = IV[15] | 0; } // prettier-ignore get() { let { v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h } = this; return [v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h]; } // prettier-ignore set(v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h) { this.v0l = v0l | 0; this.v0h = v0h | 0; this.v1l = v1l | 0; this.v1h = v1h | 0; this.v2l = v2l | 0; this.v2h = v2h | 0; this.v3l = v3l | 0; this.v3h = v3h | 0; this.v4l = v4l | 0; this.v4h = v4h | 0; this.v5l = v5l | 0; this.v5h = v5h | 0; this.v6l = v6l | 0; this.v6h = v6h | 0; this.v7l = v7l | 0; this.v7h = v7h | 0; } destroy() { super.destroy(); this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); } compress(view, offset, withLength = true) { for (let i = 0; i < 32; i++, offset += 4) BLAKE512_W[i] = view.getUint32(offset, false); this.get().forEach((v, i) => (BBUF[i] = v)); // First half from state. BBUF.set(this.constants.subarray(0, 16), 16); if (withLength) { const { h, l } = u64.fromBig(BigInt(this.length * 8)); BBUF[24] = (BBUF[24] ^ h) >>> 0; BBUF[25] = (BBUF[25] ^ l) >>> 0; BBUF[26] = (BBUF[26] ^ h) >>> 0; BBUF[27] = (BBUF[27] ^ l) >>> 0; } for (let i = 0, k = 0; i < 16; i++) { G1b(0, 4, 8, 12, BLAKE512_W, k++); G2b(0, 4, 8, 12, BLAKE512_W, k++); G1b(1, 5, 9, 13, BLAKE512_W, k++); G2b(1, 5, 9, 13, BLAKE512_W, k++); G1b(2, 6, 10, 14, BLAKE512_W, k++); G2b(2, 6, 10, 14, BLAKE512_W, k++); G1b(3, 7, 11, 15, BLAKE512_W, k++); G2b(3, 7, 11, 15, BLAKE512_W, k++); G1b(0, 5, 10, 15, BLAKE512_W, k++); G2b(0, 5, 10, 15, BLAKE512_W, k++); G1b(1, 6, 11, 12, BLAKE512_W, k++); G2b(1, 6, 11, 12, BLAKE512_W, k++); G1b(2, 7, 8, 13, BLAKE512_W, k++); G2b(2, 7, 8, 13, BLAKE512_W, k++); G1b(3, 4, 9, 14, BLAKE512_W, k++); G2b(3, 4, 9, 14, BLAKE512_W, k++); } this.v0l ^= BBUF0 ^ BBUF[16] ^ this.salt0; this.v0h ^= BBUF[1] ^ BBUF[17] ^ this.salt[1]; this.v1l ^= BBUF[2] ^ BBUF[18] ^ this.salt[2]; this.v1h ^= BBUF[3] ^ BBUF[19] ^ this.salt[3]; this.v2l ^= BBUF[4] ^ BBUF[20] ^ this.salt[4]; this.v2h ^= BBUF[5] ^ BBUF[21] ^ this.salt[5]; this.v3l ^= BBUF[6] ^ BBUF[22] ^ this.salt[6]; this.v3h ^= BBUF[7] ^ BBUF[23] ^ this.salt[7]; this.v4l ^= BBUF[8] ^ BBUF[24] ^ this.salt0; this.v4h ^= BBUF[9] ^ BBUF[25] ^ this.salt[1]; this.v5l ^= BBUF[10] ^ BBUF[26] ^ this.salt[2]; this.v5h ^= BBUF[11] ^ BBUF[27] ^ this.salt[3]; this.v6l ^= BBUF[12] ^ BBUF[28] ^ this.salt[4]; this.v6h ^= BBUF[13] ^ BBUF[29] ^ this.salt[5]; this.v7l ^= BBUF[14] ^ BBUF[30] ^ this.salt[6]; this.v7h ^= BBUF[15] ^ BBUF[31] ^ this.salt[7]; (0, utils_ts_1.clean)(BBUF, BLAKE512_W); } } class BLAKE224 extends Blake1_32 { constructor(opts = {}) { super(28, B224_IV, 0, opts); } } exports.BLAKE224 = BLAKE224; class BLAKE256 extends Blake1_32 { constructor(opts = {}) { super(32, B256_IV, 1, opts); } } exports.BLAKE256 = BLAKE256; class BLAKE384 extends Blake1_64 { constructor(opts = {}) { super(48, B384_IV, 0, opts); } } exports.BLAKE384 = BLAKE384; class BLAKE512 extends Blake1_64 { constructor(opts = {}) { super(64, B512_IV, 1, opts); } } exports.BLAKE512 = BLAKE512; /** blake1-224 hash function
blake256
Source: my-backend/node_modules/@noble/hashes/blake1.js
Signature: blake256(= (0, utils_ts_1.createOptHasher)
JSDoc:
blake1-256 hash function
blake384
Source: my-backend/node_modules/@noble/hashes/blake1.js
Signature: blake384(= (0, utils_ts_1.createOptHasher)
JSDoc:
blake1-384 hash function
blake512
Source: my-backend/node_modules/@noble/hashes/blake1.js
Signature: blake512(= (0, utils_ts_1.createOptHasher)
JSDoc:
blake1-512 hash function
blake2b
Source: my-backend/node_modules/@noble/hashes/blake2.js
Signature: blake2b(= (0, utils_ts_1.createOptHasher)
JSDoc:
blake2b (64-bit) & blake2s (8 to 32-bit) hash functions. b could have been faster, but there is no fast u64 in js, so s is 1.5x faster. @module / const _blake_ts_1 = require("./_blake.js"); const _md_ts_1 = require("./_md.js"); const u64 = require("./_u64.js"); // prettier-ignore const utils_ts_1 = require("./utils.js"); // Same as SHA512_IV, but swapped endianness: LE instead of BE. iv[1] is iv0, etc. const B2B_IV = / @PURE / Uint32Array.from([ 0xf3bcc908, 0x6a09e667, 0x84caa73b, 0xbb67ae85, 0xfe94f82b, 0x3c6ef372, 0x5f1d36f1, 0xa54ff53a, 0xade682d1, 0x510e527f, 0x2b3e6c1f, 0x9b05688c, 0xfb41bd6b, 0x1f83d9ab, 0x137e2179, 0x5be0cd19, ]); // Temporary buffer const BBUF = / @PURE / new Uint32Array(32); // Mixing function G splitted in two halfs function G1b(a, b, c, d, msg, x) { // NOTE: V is LE here const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore let Al = BBUF[2 * a], Ah = BBUF[2 * a + 1]; // prettier-ignore let Bl = BBUF[2 * b], Bh = BBUF[2 * b + 1]; // prettier-ignore let Cl = BBUF[2 * c], Ch = BBUF[2 * c + 1]; // prettier-ignore let Dl = BBUF[2 * d], Dh = BBUF[2 * d + 1]; // prettier-ignore // v[a] = (v[a] + v[b] + x) | 0; let ll = u64.add3L(Al, Bl, Xl); Ah = u64.add3H(ll, Ah, Bh, Xh); Al = ll | 0; // v[d] = rotr(v[d] ^ v[a], 32) ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); ({ Dh, Dl } = { Dh: u64.rotr32H(Dh, Dl), Dl: u64.rotr32L(Dh, Dl) }); // v[c] = (v[c] + v[d]) | 0; ({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl)); // v[b] = rotr(v[b] ^ v[c], 24) ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); ({ Bh, Bl } = { Bh: u64.rotrSH(Bh, Bl, 24), Bl: u64.rotrSL(Bh, Bl, 24) }); (BBUF[2 * a] = Al), (BBUF[2 * a + 1] = Ah); (BBUF[2 * b] = Bl), (BBUF[2 * b + 1] = Bh); (BBUF[2 * c] = Cl), (BBUF[2 * c + 1] = Ch); (BBUF[2 * d] = Dl), (BBUF[2 * d + 1] = Dh); } function G2b(a, b, c, d, msg, x) { // NOTE: V is LE here const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore let Al = BBUF[2 * a], Ah = BBUF[2 * a + 1]; // prettier-ignore let Bl = BBUF[2 * b], Bh = BBUF[2 * b + 1]; // prettier-ignore let Cl = BBUF[2 * c], Ch = BBUF[2 * c + 1]; // prettier-ignore let Dl = BBUF[2 * d], Dh = BBUF[2 * d + 1]; // prettier-ignore // v[a] = (v[a] + v[b] + x) | 0; let ll = u64.add3L(Al, Bl, Xl); Ah = u64.add3H(ll, Ah, Bh, Xh); Al = ll | 0; // v[d] = rotr(v[d] ^ v[a], 16) ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); ({ Dh, Dl } = { Dh: u64.rotrSH(Dh, Dl, 16), Dl: u64.rotrSL(Dh, Dl, 16) }); // v[c] = (v[c] + v[d]) | 0; ({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl)); // v[b] = rotr(v[b] ^ v[c], 63) ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); ({ Bh, Bl } = { Bh: u64.rotrBH(Bh, Bl, 63), Bl: u64.rotrBL(Bh, Bl, 63) }); (BBUF[2 * a] = Al), (BBUF[2 * a + 1] = Ah); (BBUF[2 * b] = Bl), (BBUF[2 * b + 1] = Bh); (BBUF[2 * c] = Cl), (BBUF[2 * c + 1] = Ch); (BBUF[2 * d] = Dl), (BBUF[2 * d + 1] = Dh); } function checkBlake2Opts(outputLen, opts = {}, keyLen, saltLen, persLen) { (0, utils_ts_1.anumber)(keyLen); if (outputLen < 0 || outputLen > keyLen) throw new Error('outputLen bigger than keyLen'); const { key, salt, personalization } = opts; if (key !== undefined && (key.length < 1 || key.length > keyLen)) throw new Error('key length must be undefined or 1..' + keyLen); if (salt !== undefined && salt.length !== saltLen) throw new Error('salt must be undefined or ' + saltLen); if (personalization !== undefined && personalization.length !== persLen) throw new Error('personalization must be undefined or ' + persLen); } / Class, from which others are subclassed. */ class BLAKE2 extends utils_ts_1.Hash { constructor(blockLen, outputLen) { super(); this.finished = false; this.destroyed = false; this.length = 0; this.pos = 0; (0, utils_ts_1.anumber)(blockLen); (0, utils_ts_1.anumber)(outputLen); this.blockLen = blockLen; this.outputLen = outputLen; this.buffer = new Uint8Array(blockLen); this.buffer32 = (0, utils_ts_1.u32)(this.buffer); } update(data) { (0, utils_ts_1.aexists)(this); data = (0, utils_ts_1.toBytes)(data); (0, utils_ts_1.abytes)(data); // Main difference with other hashes: there is flag for last block, // so we cannot process current block before we know that there // is the next one. This significantly complicates logic and reduces ability // to do zero-copy processing const { blockLen, buffer, buffer32 } = this; const len = data.length; const offset = data.byteOffset; const buf = data.buffer; for (let pos = 0; pos < len;) { // If buffer is full and we still have input (don't process last block, same as blake2s) if (this.pos === blockLen) { (0, utils_ts_1.swap32IfBE)(buffer32); this.compress(buffer32, 0, false); (0, utils_ts_1.swap32IfBE)(buffer32); this.pos = 0; } const take = Math.min(blockLen - this.pos, len - pos); const dataOffset = offset + pos; // full block && aligned to 4 bytes && not last in input if (take === blockLen && !(dataOffset % 4) && pos + take < len) { const data32 = new Uint32Array(buf, dataOffset, Math.floor((len - pos) / 4)); (0, utils_ts_1.swap32IfBE)(data32); for (let pos32 = 0; pos + blockLen < len; pos32 += buffer32.length, pos += blockLen) { this.length += blockLen; this.compress(data32, pos32, false); } (0, utils_ts_1.swap32IfBE)(data32); continue; } buffer.set(data.subarray(pos, pos + take), this.pos); this.pos += take; this.length += take; pos += take; } return this; } digestInto(out) { (0, utils_ts_1.aexists)(this); (0, utils_ts_1.aoutput)(out, this); const { pos, buffer32 } = this; this.finished = true; // Padding (0, utils_ts_1.clean)(this.buffer.subarray(pos)); (0, utils_ts_1.swap32IfBE)(buffer32); this.compress(buffer32, 0, true); (0, utils_ts_1.swap32IfBE)(buffer32); const out32 = (0, utils_ts_1.u32)(out); this.get().forEach((v, i) => (out32[i] = (0, utils_ts_1.swap8IfBE)(v))); } digest() { const { buffer, outputLen } = this; this.digestInto(buffer); const res = buffer.slice(0, outputLen); this.destroy(); return res; } _cloneInto(to) { const { buffer, length, finished, destroyed, outputLen, pos } = this; to || (to = new this.constructor({ dkLen: outputLen })); to.set(...this.get()); to.buffer.set(buffer); to.destroyed = destroyed; to.finished = finished; to.length = length; to.pos = pos; // @ts-ignore to.outputLen = outputLen; return to; } clone() { return this._cloneInto(); } } exports.BLAKE2 = BLAKE2; class BLAKE2b extends BLAKE2 { constructor(opts = {}) { const olen = opts.dkLen === undefined ? 64 : opts.dkLen; super(128, olen); // Same as SHA-512, but LE this.v0l = B2B_IV0 | 0; this.v0h = B2B_IV[1] | 0; this.v1l = B2B_IV[2] | 0; this.v1h = B2B_IV[3] | 0; this.v2l = B2B_IV[4] | 0; this.v2h = B2B_IV[5] | 0; this.v3l = B2B_IV[6] | 0; this.v3h = B2B_IV[7] | 0; this.v4l = B2B_IV[8] | 0; this.v4h = B2B_IV[9] | 0; this.v5l = B2B_IV[10] | 0; this.v5h = B2B_IV[11] | 0; this.v6l = B2B_IV[12] | 0; this.v6h = B2B_IV[13] | 0; this.v7l = B2B_IV[14] | 0; this.v7h = B2B_IV[15] | 0; checkBlake2Opts(olen, opts, 64, 16, 16); let { key, personalization, salt } = opts; let keyLength = 0; if (key !== undefined) { key = (0, utils_ts_1.toBytes)(key); keyLength = key.length; } this.v0l ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24); if (salt !== undefined) { salt = (0, utils_ts_1.toBytes)(salt); const slt = (0, utils_ts_1.u32)(salt); this.v4l ^= (0, utils_ts_1.swap8IfBE)(slt0); this.v4h ^= (0, utils_ts_1.swap8IfBE)(slt[1]); this.v5l ^= (0, utils_ts_1.swap8IfBE)(slt[2]); this.v5h ^= (0, utils_ts_1.swap8IfBE)(slt[3]); } if (personalization !== undefined) { personalization = (0, utils_ts_1.toBytes)(personalization); const pers = (0, utils_ts_1.u32)(personalization); this.v6l ^= (0, utils_ts_1.swap8IfBE)(pers0); this.v6h ^= (0, utils_ts_1.swap8IfBE)(pers[1]); this.v7l ^= (0, utils_ts_1.swap8IfBE)(pers[2]); this.v7h ^= (0, utils_ts_1.swap8IfBE)(pers[3]); } if (key !== undefined) { // Pad to blockLen and update const tmp = new Uint8Array(this.blockLen); tmp.set(key); this.update(tmp); } } // prettier-ignore get() { let { v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h } = this; return [v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h]; } // prettier-ignore set(v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h) { this.v0l = v0l | 0; this.v0h = v0h | 0; this.v1l = v1l | 0; this.v1h = v1h | 0; this.v2l = v2l | 0; this.v2h = v2h | 0; this.v3l = v3l | 0; this.v3h = v3h | 0; this.v4l = v4l | 0; this.v4h = v4h | 0; this.v5l = v5l | 0; this.v5h = v5h | 0; this.v6l = v6l | 0; this.v6h = v6h | 0; this.v7l = v7l | 0; this.v7h = v7h | 0; } compress(msg, offset, isLast) { this.get().forEach((v, i) => (BBUF[i] = v)); // First half from state. BBUF.set(B2B_IV, 16); // Second half from IV. let { h, l } = u64.fromBig(BigInt(this.length)); BBUF[24] = B2B_IV[8] ^ l; // Low word of the offset. BBUF[25] = B2B_IV[9] ^ h; // High word. // Invert all bits for last block if (isLast) { BBUF[28] = ~BBUF[28]; BBUF[29] = ~BBUF[29]; } let j = 0; const s = _blake_ts_1.BSIGMA; for (let i = 0; i < 12; i++) { G1b(0, 4, 8, 12, msg, offset + 2 * s[j++]); G2b(0, 4, 8, 12, msg, offset + 2 * s[j++]); G1b(1, 5, 9, 13, msg, offset + 2 * s[j++]); G2b(1, 5, 9, 13, msg, offset + 2 * s[j++]); G1b(2, 6, 10, 14, msg, offset + 2 * s[j++]); G2b(2, 6, 10, 14, msg, offset + 2 * s[j++]); G1b(3, 7, 11, 15, msg, offset + 2 * s[j++]); G2b(3, 7, 11, 15, msg, offset + 2 * s[j++]); G1b(0, 5, 10, 15, msg, offset + 2 * s[j++]); G2b(0, 5, 10, 15, msg, offset + 2 * s[j++]); G1b(1, 6, 11, 12, msg, offset + 2 * s[j++]); G2b(1, 6, 11, 12, msg, offset + 2 * s[j++]); G1b(2, 7, 8, 13, msg, offset + 2 * s[j++]); G2b(2, 7, 8, 13, msg, offset + 2 * s[j++]); G1b(3, 4, 9, 14, msg, offset + 2 * s[j++]); G2b(3, 4, 9, 14, msg, offset + 2 * s[j++]); } this.v0l ^= BBUF0 ^ BBUF[16]; this.v0h ^= BBUF[1] ^ BBUF[17]; this.v1l ^= BBUF[2] ^ BBUF[18]; this.v1h ^= BBUF[3] ^ BBUF[19]; this.v2l ^= BBUF[4] ^ BBUF[20]; this.v2h ^= BBUF[5] ^ BBUF[21]; this.v3l ^= BBUF[6] ^ BBUF[22]; this.v3h ^= BBUF[7] ^ BBUF[23]; this.v4l ^= BBUF[8] ^ BBUF[24]; this.v4h ^= BBUF[9] ^ BBUF[25]; this.v5l ^= BBUF[10] ^ BBUF[26]; this.v5h ^= BBUF[11] ^ BBUF[27]; this.v6l ^= BBUF[12] ^ BBUF[28]; this.v6h ^= BBUF[13] ^ BBUF[29]; this.v7l ^= BBUF[14] ^ BBUF[30]; this.v7h ^= BBUF[15] ^ BBUF[31]; (0, utils_ts_1.clean)(BBUF); } destroy() { this.destroyed = true; (0, utils_ts_1.clean)(this.buffer32); this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); } } exports.BLAKE2b = BLAKE2b; / Blake2b hash function. 64-bit. 1.5x slower than blake2s in JS. @param msg - message that would be hashed @param opts - dkLen output length, key for MAC mode, salt, personalization
blake2s
Source: my-backend/node_modules/@noble/hashes/blake2.js
Signature: blake2s(= (0, utils_ts_1.createOptHasher)
JSDoc:
Blake2s hash function. Focuses on 8-bit to 32-bit platforms. 1.5x faster than blake2b in JS. @param msg - message that would be hashed @param opts - dkLen output length, key for MAC mode, salt, personalization
BLAKE2b
Source: my-backend/node_modules/@noble/hashes/blake2b.js
Signature: BLAKE2b(= blake2_ts_1.BLAKE2b;
/** @deprecated Use import fromnoble/hashes/blake2module */
exports.blake2b = blake2_ts_1.blake2b;
//# sourceMappingURL=blake2b.js.map)
JSDoc:
Blake2b hash function. Focuses on 64-bit platforms, but in JS speed different from Blake2s is negligible.
@module
@deprecated
/
const blake2_ts_1 = require("./blake2.js");
/** @deprecated Use import from noble/hashes/blake2 module
B2S_IV
Source: my-backend/node_modules/@noble/hashes/blake2s.js
Signature: B2S_IV(= _md_ts_1.SHA256_IV;
/** @deprecated Use import fromnoble/hashes/blake2module */
exports.G1s = _blake_ts_1.G1s;
/** @deprecated Use import fromnoble/hashes/blake2module */
exports.G2s = _blake_ts_1.G2s;
/** @deprecated Use import fromnoble/hashes/blake2module */
exports.compress = blake2_ts_1.compress;
/** @deprecated Use import fromnoble/hashes/blake2module */
exports.BLAKE2s = blake2_ts_1.BLAKE2s;
/** @deprecated Use import fromnoble/hashes/blake2module */
exports.blake2s = blake2_ts_1.blake2s;
//# sourceMappingURL=blake2s.js.map)
JSDoc:
Blake2s hash function. Focuses on 8-bit to 32-bit platforms. blake2b for 64-bit, but in JS it is slower.
@module
@deprecated
/
const _blake_ts_1 = require("./_blake.js");
const _md_ts_1 = require("./_md.js");
const blake2_ts_1 = require("./blake2.js");
/** @deprecated Use import from noble/hashes/blake2 module
blake3
Source: my-backend/node_modules/@noble/hashes/blake3.js
Signature: blake3(= (0, utils_ts_1.createXOFer)
JSDoc:
Blake3 fast hash is Blake2 with reduced security (round count). Can also be used as MAC & KDF.
It is advertised as "the fastest cryptographic hash". However, it isn't true in JS. Why is this so slow? While it should be 6x faster than blake2b, perf diff is only 20%:
- There is only 30% reduction in number of rounds from blake2s
- Speed-up comes from tree structure, which is parallelized using SIMD & threading. These features are not present in JS, so we only get overhead from trees.
- Parallelization only happens on 1024-byte chunks: there is no benefit for small inputs.
- It is still possible to make it faster using: a) loop unrolling b) web workers c) wasm
@module
/
const md_ts_1 = require("./_md.js");
const _u64_ts_1 = require("./_u64.js");
const blake2_ts_1 = require("./blake2.js");
// prettier-ignore
const utils_ts_1 = require("./utils.js");
// Flag bitset
const B3_Flags = {
CHUNK_START: 0b1,
CHUNK_END: 0b10,
PARENT: 0b100,
ROOT: 0b1000,
KEYED_HASH: 0b10000,
DERIVE_KEY_CONTEXT: 0b100000,
DERIVE_KEY_MATERIAL: 0b1000000,
};
const B3_IV = _md_ts_1.SHA256_IV.slice();
const B3_SIGMA = / @PURE / (() => {
const Id = Array.from({ length: 16 }, (, i) => i);
const permute = (arr) => [2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8].map((i) => arr[i]);
const res = [];
for (let i = 0, v = Id; i < 7; i++, v = permute(v))
res.push(...v);
return Uint8Array.from(res);
})();
/ Blake3 hash. Can be used as MAC and KDF. */
class BLAKE3 extends blake2_ts_1.BLAKE2 {
constructor(opts = {}, flags = 0) {
super(64, opts.dkLen === undefined ? 32 : opts.dkLen);
this.chunkPos = 0; // Position of current block in chunk
this.chunksDone = 0; // How many chunks we already have
this.flags = 0 | 0;
this.stack = [];
// Output
this.posOut = 0;
this.bufferOut32 = new Uint32Array(16);
this.chunkOut = 0; // index of output chunk
this.enableXOF = true;
const { key, context } = opts;
const hasContext = context !== undefined;
if (key !== undefined) {
if (hasContext)
throw new Error('Only "key" or "context" can be specified at same time');
const k = (0, utils_ts_1.toBytes)(key).slice();
(0, utils_ts_1.abytes)(k, 32);
this.IV = (0, utils_ts_1.u32)(k);
(0, utils_ts_1.swap32IfBE)(this.IV);
this.flags = flags | B3_Flags.KEYED_HASH;
}
else if (hasContext) {
const ctx = (0, utils_ts_1.toBytes)(context);
const contextKey = new BLAKE3({ dkLen: 32 }, B3_Flags.DERIVE_KEY_CONTEXT)
.update(ctx)
.digest();
this.IV = (0, utils_ts_1.u32)(contextKey);
(0, utils_ts_1.swap32IfBE)(this.IV);
this.flags = flags | B3_Flags.DERIVE_KEY_MATERIAL;
}
else {
this.IV = B3_IV.slice();
this.flags = flags;
}
this.state = this.IV.slice();
this.bufferOut = (0, utils_ts_1.u8)(this.bufferOut32);
}
// Unused
get() {
return [];
}
set() { }
b2Compress(counter, flags, buf, bufPos = 0) {
const { state: s, pos } = this;
const { h, l } = (0, _u64_ts_1.fromBig)(BigInt(counter), true);
// prettier-ignore
const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = (0, blake2_ts_1.compress)(B3_SIGMA, bufPos, buf, 7, s0, s[1], s[2], s[3], s[4], s[5], s[6], s[7], B3_IV0, B3_IV[1], B3_IV[2], B3_IV[3], h, l, pos, flags);
s0 = v0 ^ v8;
s[1] = v1 ^ v9;
s[2] = v2 ^ v10;
s[3] = v3 ^ v11;
s[4] = v4 ^ v12;
s[5] = v5 ^ v13;
s[6] = v6 ^ v14;
s[7] = v7 ^ v15;
}
compress(buf, bufPos = 0, isLast = false) {
// Compress last block
let flags = this.flags;
if (!this.chunkPos)
flags |= B3_Flags.CHUNK_START;
if (this.chunkPos === 15 || isLast)
flags |= B3_Flags.CHUNK_END;
if (!isLast)
this.pos = this.blockLen;
this.b2Compress(this.chunksDone, flags, buf, bufPos);
this.chunkPos += 1;
// If current block is last in chunk (16 blocks), then compress chunks
if (this.chunkPos === 16 || isLast) {
let chunk = this.state;
this.state = this.IV.slice();
// If not the last one, compress only when there are trailing zeros in chunk counter
// chunks used as binary tree where current stack is path. Zero means current leaf is finished and can be compressed.
// 1 (001) - leaf not finished (just push current chunk to stack)
// 2 (010) - leaf finished at depth=1 (merge with last elm on stack and push back)
// 3 (011) - last leaf not finished
// 4 (100) - leafs finished at depth=1 and depth=2
for (let last, chunks = this.chunksDone + 1; isLast || !(chunks & 1); chunks >>= 1) {
if (!(last = this.stack.pop()))
break;
this.buffer32.set(last, 0);
this.buffer32.set(chunk, 8);
this.pos = this.blockLen;
this.b2Compress(0, this.flags | B3_Flags.PARENT, this.buffer32, 0);
chunk = this.state;
this.state = this.IV.slice();
}
this.chunksDone++;
this.chunkPos = 0;
this.stack.push(chunk);
}
this.pos = 0;
}
_cloneInto(to) {
to = super._cloneInto(to);
const { IV, flags, state, chunkPos, posOut, chunkOut, stack, chunksDone } = this;
to.state.set(state.slice());
to.stack = stack.map((i) => Uint32Array.from(i));
to.IV.set(IV);
to.flags = flags;
to.chunkPos = chunkPos;
to.chunksDone = chunksDone;
to.posOut = posOut;
to.chunkOut = chunkOut;
to.enableXOF = this.enableXOF;
to.bufferOut32.set(this.bufferOut32);
return to;
}
destroy() {
this.destroyed = true;
(0, utils_ts_1.clean)(this.state, this.buffer32, this.IV, this.bufferOut32);
(0, utils_ts_1.clean)(...this.stack);
}
// Same as b2Compress, but doesn't modify state and returns 16 u32 array (instead of 8)
b2CompressOut() {
const { state: s, pos, flags, buffer32, bufferOut32: out32 } = this;
const { h, l } = (0, _u64_ts_1.fromBig)(BigInt(this.chunkOut++));
(0, utils_ts_1.swap32IfBE)(buffer32);
// prettier-ignore
const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = (0, blake2_ts_1.compress)(B3_SIGMA, 0, buffer32, 7, s0, s[1], s[2], s[3], s[4], s[5], s[6], s[7], B3_IV0, B3_IV[1], B3_IV[2], B3_IV[3], l, h, pos, flags);
out320 = v0 ^ v8;
out32[1] = v1 ^ v9;
out32[2] = v2 ^ v10;
out32[3] = v3 ^ v11;
out32[4] = v4 ^ v12;
out32[5] = v5 ^ v13;
out32[6] = v6 ^ v14;
out32[7] = v7 ^ v15;
out32[8] = s0 ^ v8;
out32[9] = s[1] ^ v9;
out32[10] = s[2] ^ v10;
out32[11] = s[3] ^ v11;
out32[12] = s[4] ^ v12;
out32[13] = s[5] ^ v13;
out32[14] = s[6] ^ v14;
out32[15] = s[7] ^ v15;
(0, utils_ts_1.swap32IfBE)(buffer32);
(0, utils_ts_1.swap32IfBE)(out32);
this.posOut = 0;
}
finish() {
if (this.finished)
return;
this.finished = true;
// Padding
(0, utils_ts_1.clean)(this.buffer.subarray(this.pos));
// Process last chunk
let flags = this.flags | B3_Flags.ROOT;
if (this.stack.length) {
flags |= B3_Flags.PARENT;
(0, utils_ts_1.swap32IfBE)(this.buffer32);
this.compress(this.buffer32, 0, true);
(0, utils_ts_1.swap32IfBE)(this.buffer32);
this.chunksDone = 0;
this.pos = this.blockLen;
}
else {
flags |= (!this.chunkPos ? B3_Flags.CHUNK_START : 0) | B3_Flags.CHUNK_END;
}
this.flags = flags;
this.b2CompressOut();
}
writeInto(out) {
(0, utils_ts_1.aexists)(this, false);
(0, utils_ts_1.abytes)(out);
this.finish();
const { blockLen, bufferOut } = this;
for (let pos = 0, len = out.length; pos < len;) {
if (this.posOut >= blockLen)
this.b2CompressOut();
const take = Math.min(blockLen - this.posOut, len - pos);
out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
this.posOut += take;
pos += take;
}
return out;
}
xofInto(out) {
if (!this.enableXOF)
throw new Error('XOF is not possible after digest call');
return this.writeInto(out);
}
xof(bytes) {
(0, utils_ts_1.anumber)(bytes);
return this.xofInto(new Uint8Array(bytes));
}
digestInto(out) {
(0, utils_ts_1.aoutput)(out, this);
if (this.finished)
throw new Error('digest() was already called');
this.enableXOF = false;
this.writeInto(out);
this.destroy();
return out;
}
digest() {
return this.digestInto(new Uint8Array(this.outputLen));
}
}
exports.BLAKE3 = BLAKE3;
/
BLAKE3 hash function. Can be used as MAC and KDF.
@param msg - message that would be hashed
@param opts -
dkLenfor output length,keyfor MAC mode,contextfor KDF mode @example const data = new Uint8Array(32); const hash = blake3(data); const mac = blake3(data, { key: new Uint8Array(32) }); const kdf = blake3(data, { context: 'application name' });
setBigUint64
Source: my-backend/node_modules/@noble/hashes/esm/_md.js
Signature: setBigUint64(view, byteOffset, value, isLE)
JSDoc:
Internal Merkle-Damgard hash utils. @module / import { Hash, abytes, aexists, aoutput, clean, createView, toBytes } from "./utils.js"; /** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64
Chi
Source: my-backend/node_modules/@noble/hashes/esm/_md.js
Signature: Chi(a, b, c)
JSDoc:
Choice: a ? b : c
Maj
Source: my-backend/node_modules/@noble/hashes/esm/_md.js
Signature: Maj(a, b, c)
JSDoc:
Majority function, true if any two inputs is true.
deriveMainSeed
Source: my-backend/node_modules/@noble/hashes/esm/eskdf.js
Signature: deriveMainSeed(username, password)
JSDoc:
Experimental KDF for AES.
/
import { hkdf } from "./hkdf.js";
import { pbkdf2 as _pbkdf2 } from "./pbkdf2.js";
import { scrypt as _scrypt } from "./scrypt.js";
import { sha256 } from "./sha256.js";
import { abytes, bytesToHex, clean, createView, hexToBytes, kdfInputToBytes } from "./utils.js";
// A tiny KDF for various applications like AES key-gen.
// Uses HKDF in a non-standard way, so it's not "KDF-secure", only "PRF-secure".
// Which is good enough: assume sha2-256 retained preimage resistance.
const SCRYPT_FACTOR = 2 ** 19;
const PBKDF2_FACTOR = 2 ** 17;
// Scrypt KDF
export function scrypt(password, salt) {
return _scrypt(password, salt, { N: SCRYPT_FACTOR, r: 8, p: 1, dkLen: 32 });
}
// PBKDF2-HMAC-SHA256
export function pbkdf2(password, salt) {
return _pbkdf2(sha256, password, salt, { c: PBKDF2_FACTOR, dkLen: 32 });
}
// Combines two 32-byte byte arrays
function xor32(a, b) {
abytes(a, 32);
abytes(b, 32);
const arr = new Uint8Array(32);
for (let i = 0; i < 32; i++) {
arr[i] = a[i] ^ b[i];
}
return arr;
}
function strHasLength(str, min, max) {
return typeof str === 'string' && str.length >= min && str.length <= max;
}
/**
Derives main seed. Takes a lot of time. Prefer eskdf method instead.
extract
Source: my-backend/node_modules/@noble/hashes/esm/hkdf.js
Signature: extract(hash, ikm, salt)
JSDoc:
HKDF (RFC 5869): extract + expand in one step.
See https://soatok.blog/2021/11/17/understanding-hkdf/.
@module
/
import { hmac } from "./hmac.js";
import { ahash, anumber, clean, toBytes } from "./utils.js";
/**
HKDF-extract from spec. Less important part. HKDF-Extract(IKM, salt) -> PRK
Arguments position differs from spec (IKM is first one, since it is not optional)
@param hash - hash function that would be used (e.g. sha256)
@param ikm - input keying material, the initial key
@param salt - optional salt value (a non-secret random value)
expand
Source: my-backend/node_modules/@noble/hashes/esm/hkdf.js
Signature: expand(hash, prk, info, length = 32)
JSDoc:
HKDF-expand from the spec. The most important part. HKDF-Expand(PRK, info, L) -> OKM
@param hash - hash function that would be used (e.g. sha256)
@param prk - a pseudorandom key of at least HashLen octets (usually, the output from the extract step)
@param info - optional context and application specific information (can be a zero-length string)
@param length - length of output keying material in bytes
pbkdf2
Source: my-backend/node_modules/@noble/hashes/esm/pbkdf2.js
Signature: pbkdf2(hash, password, salt, opts)
JSDoc:
PBKDF (RFC 2898). Can be used to create a key from password and salt. @module / import { hmac } from "./hmac.js"; // prettier-ignore import { ahash, anumber, asyncLoop, checkOpts, clean, createView, Hash, kdfInputToBytes } from "./utils.js"; // Common prologue and epilogue for sync/async functions function pbkdf2Init(hash, _password, _salt, _opts) { ahash(hash); const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts); const { c, dkLen, asyncTick } = opts; anumber(c); anumber(dkLen); anumber(asyncTick); if (c < 1) throw new Error('iterations (c) should be >= 1'); const password = kdfInputToBytes(_password); const salt = kdfInputToBytes(_salt); // DK = PBKDF2(PRF, Password, Salt, c, dkLen); const DK = new Uint8Array(dkLen); // U1 = PRF(Password, Salt + INT_32_BE(i)) const PRF = hmac.create(hash, password); const PRFSalt = PRF._cloneInto().update(salt); return { c, dkLen, asyncTick, DK, PRF, PRFSalt }; } function pbkdf2Output(PRF, PRFSalt, DK, prfW, u) { PRF.destroy(); PRFSalt.destroy(); if (prfW) prfW.destroy(); clean(u); return DK; } /** PBKDF2-HMAC: RFC 2898 key derivation function @param hash - hash function that would be used e.g. sha256 @param password - password from which a derived key is generated @param salt - cryptographic salt @param opts - {c, dkLen} where c is work factor and dkLen is output message size @example const key = pbkdf2(sha256, 'password', 'salt', { dkLen: 32, c: Math.pow(2, 18) });
scrypt
Source: my-backend/node_modules/@noble/hashes/esm/scrypt.js
Signature: scrypt(password, salt, opts)
JSDoc:
RFC 7914 Scrypt KDF. Can be used to create a key from password and salt.
@module
/
import { pbkdf2 } from "./pbkdf2.js";
import { sha256 } from "./sha2.js";
// prettier-ignore
import { anumber, asyncLoop, checkOpts, clean, rotl, swap32IfBE, u32 } from "./utils.js";
// The main Scrypt loop: uses Salsa extensively.
// Six versions of the function were tried, this is the fastest one.
// prettier-ignore
function XorAndSalsa(prev, pi, input, ii, out, oi) {
// Based on https://cr.yp.to/salsa20.html
// Xor blocks
let y00 = prev[pi++] ^ input[ii++], y01 = prev[pi++] ^ input[ii++];
let y02 = prev[pi++] ^ input[ii++], y03 = prev[pi++] ^ input[ii++];
let y04 = prev[pi++] ^ input[ii++], y05 = prev[pi++] ^ input[ii++];
let y06 = prev[pi++] ^ input[ii++], y07 = prev[pi++] ^ input[ii++];
let y08 = prev[pi++] ^ input[ii++], y09 = prev[pi++] ^ input[ii++];
let y10 = prev[pi++] ^ input[ii++], y11 = prev[pi++] ^ input[ii++];
let y12 = prev[pi++] ^ input[ii++], y13 = prev[pi++] ^ input[ii++];
let y14 = prev[pi++] ^ input[ii++], y15 = prev[pi++] ^ input[ii++];
// Save state to temporary variables (salsa)
let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15;
// Main loop (salsa)
for (let i = 0; i < 8; i += 2) {
x04 ^= rotl(x00 + x12 | 0, 7);
x08 ^= rotl(x04 + x00 | 0, 9);
x12 ^= rotl(x08 + x04 | 0, 13);
x00 ^= rotl(x12 + x08 | 0, 18);
x09 ^= rotl(x05 + x01 | 0, 7);
x13 ^= rotl(x09 + x05 | 0, 9);
x01 ^= rotl(x13 + x09 | 0, 13);
x05 ^= rotl(x01 + x13 | 0, 18);
x14 ^= rotl(x10 + x06 | 0, 7);
x02 ^= rotl(x14 + x10 | 0, 9);
x06 ^= rotl(x02 + x14 | 0, 13);
x10 ^= rotl(x06 + x02 | 0, 18);
x03 ^= rotl(x15 + x11 | 0, 7);
x07 ^= rotl(x03 + x15 | 0, 9);
x11 ^= rotl(x07 + x03 | 0, 13);
x15 ^= rotl(x11 + x07 | 0, 18);
x01 ^= rotl(x00 + x03 | 0, 7);
x02 ^= rotl(x01 + x00 | 0, 9);
x03 ^= rotl(x02 + x01 | 0, 13);
x00 ^= rotl(x03 + x02 | 0, 18);
x06 ^= rotl(x05 + x04 | 0, 7);
x07 ^= rotl(x06 + x05 | 0, 9);
x04 ^= rotl(x07 + x06 | 0, 13);
x05 ^= rotl(x04 + x07 | 0, 18);
x11 ^= rotl(x10 + x09 | 0, 7);
x08 ^= rotl(x11 + x10 | 0, 9);
x09 ^= rotl(x08 + x11 | 0, 13);
x10 ^= rotl(x09 + x08 | 0, 18);
x12 ^= rotl(x15 + x14 | 0, 7);
x13 ^= rotl(x12 + x15 | 0, 9);
x14 ^= rotl(x13 + x12 | 0, 13);
x15 ^= rotl(x14 + x13 | 0, 18);
}
// Write output (salsa)
out[oi++] = (y00 + x00) | 0;
out[oi++] = (y01 + x01) | 0;
out[oi++] = (y02 + x02) | 0;
out[oi++] = (y03 + x03) | 0;
out[oi++] = (y04 + x04) | 0;
out[oi++] = (y05 + x05) | 0;
out[oi++] = (y06 + x06) | 0;
out[oi++] = (y07 + x07) | 0;
out[oi++] = (y08 + x08) | 0;
out[oi++] = (y09 + x09) | 0;
out[oi++] = (y10 + x10) | 0;
out[oi++] = (y11 + x11) | 0;
out[oi++] = (y12 + x12) | 0;
out[oi++] = (y13 + x13) | 0;
out[oi++] = (y14 + x14) | 0;
out[oi++] = (y15 + x15) | 0;
}
function BlockMix(input, ii, out, oi, r) {
// The block B is r 128-byte chunks (which is equivalent of 2r 64-byte chunks)
let head = oi + 0;
let tail = oi + 16 * r;
for (let i = 0; i < 16; i++)
out[tail + i] = input[ii + (2 * r - 1) * 16 + i]; // X ← B[2r−1]
for (let i = 0; i < r; i++, head += 16, ii += 16) {
// We write odd & even Yi at same time. Even: 0bXXXXX0 Odd: 0bXXXXX1
XorAndSalsa(out, tail, input, ii, out, head); // head[i] = Salsa(blockIn[2i] ^ tail[i-1])
if (i > 0)
tail += 16; // First iteration overwrites tmp value in tail
XorAndSalsa(out, head, input, (ii += 16), out, tail); // tail[i] = Salsa(blockIn[2i+1] ^ head[i])
}
}
// Common prologue and epilogue for sync/async functions
function scryptInit(password, salt, _opts) {
// Maxmem - 1GB+1KB by default
const opts = checkOpts({
dkLen: 32,
asyncTick: 10,
maxmem: 1024 ** 3 + 1024,
}, _opts);
const { N, r, p, dkLen, asyncTick, maxmem, onProgress } = opts;
anumber(N);
anumber(r);
anumber(p);
anumber(dkLen);
anumber(asyncTick);
anumber(maxmem);
if (onProgress !== undefined && typeof onProgress !== 'function')
throw new Error('progressCb should be function');
const blockSize = 128 * r;
const blockSize32 = blockSize / 4;
// Max N is 2^32 (Integrify is 32-bit). Real limit is 2^22: JS engines Uint8Array limit is 4GB in 2024.
// Spec check N >= 2^(blockSize / 8) is not done for compat with popular libs,
// which used incorrect r: 1, p: 8. Also, the check seems to be a spec error:
// https://www.rfc-editor.org/errata_search.php?rfc=7914
const pow32 = Math.pow(2, 32);
if (N <= 1 || (N & (N - 1)) !== 0 || N > pow32) {
throw new Error('Scrypt: N must be larger than 1, a power of 2, and less than 2^32');
}
if (p < 0 || p > ((pow32 - 1) * 32) / blockSize) {
throw new Error('Scrypt: p must be a positive integer less than or equal to ((2^32 - 1) * 32) / (128 * r)');
}
if (dkLen < 0 || dkLen > (pow32 - 1) * 32) {
throw new Error('Scrypt: dkLen should be positive integer less than or equal to (2^32 - 1) * 32');
}
const memUsed = blockSize * (N + p);
if (memUsed > maxmem) {
throw new Error('Scrypt: memused is bigger than maxMem. Expected 128 * r * (N + p) > maxmem of ' + maxmem);
}
// [B0...Bp−1] ← PBKDF2HMAC-SHA256(Passphrase, Salt, 1, blockSizeParallelizationFactor)
// Since it has only one iteration there is no reason to use async variant
const B = pbkdf2(sha256, password, salt, { c: 1, dkLen: blockSize * p });
const B32 = u32(B);
// Re-used between parallel iterations. Array(iterations) of B
const V = u32(new Uint8Array(blockSize * N));
const tmp = u32(new Uint8Array(blockSize));
let blockMixCb = () => { };
if (onProgress) {
const totalBlockMix = 2 * N * p;
// Invoke callback if progress changes from 10.01 to 10.02
// Allows to draw smooth progress bar on up to 8K screen
const callbackPer = Math.max(Math.floor(totalBlockMix / 10000), 1);
let blockMixCnt = 0;
blockMixCb = () => {
blockMixCnt++;
if (onProgress && (!(blockMixCnt % callbackPer) || blockMixCnt === totalBlockMix))
onProgress(blockMixCnt / totalBlockMix);
};
}
return { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick };
}
function scryptOutput(password, dkLen, B, V, tmp) {
const res = pbkdf2(sha256, password, B, { c: 1, dkLen });
clean(B, V, tmp);
return res;
}
/
Scrypt KDF from RFC 7914.
@param password - pass
@param salt - salt
@param opts - parameters
- N is cpu/mem work factor (power of 2 e.g. 218)
- r is block size (8 is common), fine-tunes sequential memory read size and performance
- p is parallelization factor (1 is common)
- dkLen is output key length in bytes e.g. 32.
- asyncTick - (default: 10) max time in ms for which async function can block execution
- maxmem - (default: 1024 ** 3 + 1024 aka 1GB+1KB). A limit that the app could use for scrypt
- onProgress - callback function that would be executed for progress report
@returns Derived key
@example
scrypt('password', 'salt', { N: 2*18, r: 8, p: 1, dkLen: 32 });
keccakP
Source: my-backend/node_modules/@noble/hashes/esm/sha3.js
Signature: keccakP(s, rounds = 24)
JSDoc:
SHA3 (keccak) hash function, based on a new "Sponge function" design. Different from older hashes, the internal state is bigger than output size.
Check out FIPS-202, Website, the differences between SHA-3 and Keccak.
Check out sha3-addons module for cSHAKE, k12, and others.
@module
/
import { rotlBH, rotlBL, rotlSH, rotlSL, split } from "./_u64.js";
// prettier-ignore
import { abytes, aexists, anumber, aoutput, clean, createHasher, createXOFer, Hash, swap32IfBE, toBytes, u32 } from "./utils.js";
// No PURE annotations in sha3 header:
// EVERYTHING is in fact used on every export.
// Various per round constants calculations
const _0n = BigInt(0);
const _1n = BigInt(1);
const _2n = BigInt(2);
const _7n = BigInt(7);
const _256n = BigInt(256);
const _0x71n = BigInt(0x71);
const SHA3_PI = [];
const SHA3_ROTL = [];
const _SHA3_IOTA = [];
for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {
// Pi
[x, y] = [y, (2 * x + 3 * y) % 5];
SHA3_PI.push(2 * (5 * y + x));
// Rotational
SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);
// Iota
let t = _0n;
for (let j = 0; j < 7; j++) {
R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n;
if (R & _2n)
t ^= _1n << ((_1n << / @PURE / BigInt(j)) - _1n);
}
_SHA3_IOTA.push(t);
}
const IOTAS = split(_SHA3_IOTA, true);
const SHA3_IOTA_H = IOTAS0;
const SHA3_IOTA_L = IOTAS[1];
// Left rotation (without 0, 32, 64)
const rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s));
const rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s));
/** keccakf1600 internal function, additionally allows to adjust round count.
isBytes
Source: my-backend/node_modules/@noble/hashes/esm/utils.js
Signature: isBytes(a)
JSDoc:
Utilities for hex, bytes, CSPRNG.
@module
/
/! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) /
// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
// node.js versions earlier than v19 don't declare it in global scope.
// For node.js, package.json#exports field mapping rewrites import
// from crypto to cryptoNode, which imports native module.
// Makes the utils un-importable in browsers without a bundler.
// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.
import { crypto } from '@noble/hashes/crypto';
/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.
anumber
Source: my-backend/node_modules/@noble/hashes/esm/utils.js
Signature: anumber(n)
JSDoc:
Asserts something is positive integer.
abytes
Source: my-backend/node_modules/@noble/hashes/esm/utils.js
Signature: abytes(b, ...lengths)
JSDoc:
Asserts something is Uint8Array.
ahash
Source: my-backend/node_modules/@noble/hashes/esm/utils.js
Signature: ahash(h)
JSDoc:
Asserts something is hash
aexists
Source: my-backend/node_modules/@noble/hashes/esm/utils.js
Signature: aexists(instance, checkFinished = true)
JSDoc:
Asserts a hash instance has not been destroyed / finished
aoutput
Source: my-backend/node_modules/@noble/hashes/esm/utils.js
Signature: aoutput(out, instance)
JSDoc:
Asserts output is properly-sized byte array
u8
Source: my-backend/node_modules/@noble/hashes/esm/utils.js
Signature: u8(arr)
JSDoc:
Cast u8 / u16 / u32 to u8.
u32
Source: my-backend/node_modules/@noble/hashes/esm/utils.js
Signature: u32(arr)
JSDoc:
Cast u8 / u16 / u32 to u32.
clean
Source: my-backend/node_modules/@noble/hashes/esm/utils.js
Signature: clean(...arrays)
JSDoc:
Zeroize a byte array. Warning: JS provides no guarantees.
createView
Source: my-backend/node_modules/@noble/hashes/esm/utils.js
Signature: createView(arr)
JSDoc:
Create DataView of an array for easy byte-level manipulation.
rotr
Source: my-backend/node_modules/@noble/hashes/esm/utils.js
Signature: rotr(word, shift)
JSDoc:
The rotate right (circular right shift) operation for uint32
rotl
Source: my-backend/node_modules/@noble/hashes/esm/utils.js
Signature: rotl(word, shift)
JSDoc:
The rotate left (circular left shift) operation for uint32
byteSwap
Source: my-backend/node_modules/@noble/hashes/esm/utils.js
Signature: byteSwap(word)
JSDoc:
Is current platform little-endian? Most are. Big-Endian platform: IBM / export const isLE = / @PURE / (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)0 === 0x44)(); /* The byte swap operation for uint32
byteSwap32
Source: my-backend/node_modules/@noble/hashes/esm/utils.js
Signature: byteSwap32(arr)
JSDoc:
Conditionally byte swap if on a big-endian platform / export const swap8IfBE = isLE ? (n) => n : (n) => byteSwap(n); / @deprecated / export const byteSwapIfBE = swap8IfBE; /** In place byte swap for Uint32Array
bytesToHex
Source: my-backend/node_modules/@noble/hashes/esm/utils.js
Signature: bytesToHex(bytes)
JSDoc:
Convert byte array to hex string. Uses built-in function, when available. @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
hexToBytes
Source: my-backend/node_modules/@noble/hashes/esm/utils.js
Signature: hexToBytes(hex)
JSDoc:
Convert hex string to byte array. Uses built-in function, when available. @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
utf8ToBytes
Source: my-backend/node_modules/@noble/hashes/esm/utils.js
Signature: utf8ToBytes(str)
JSDoc:
There is no setImmediate in browser and setTimeout is slow. Call of async fn will return Promise, which will be fullfiled only on next scheduler queue processing step and this is exactly what we need. / export const nextTick = async () => { }; / Returns control to thread each 'tick' ms to avoid blocking. */ export async function asyncLoop(iters, tick, cb) { let ts = Date.now(); for (let i = 0; i < iters; i++) { cb(i); // Date.now() is not monotonic, so in case if clock goes backwards we return return control too const diff = Date.now() - ts; if (diff >= 0 && diff < tick) continue; await nextTick(); ts += diff; } } / Converts string to bytes using UTF8 encoding. @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])
bytesToUtf8
Source: my-backend/node_modules/@noble/hashes/esm/utils.js
Signature: bytesToUtf8(bytes)
JSDoc:
Converts bytes to string using UTF8 encoding. @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'
toBytes
Source: my-backend/node_modules/@noble/hashes/esm/utils.js
Signature: toBytes(data)
JSDoc:
Normalizes (non-hex) string or Uint8Array to Uint8Array. Warning: when Uint8Array is passed, it would NOT get copied. Keep in mind for future mutable operations.
kdfInputToBytes
Source: my-backend/node_modules/@noble/hashes/esm/utils.js
Signature: kdfInputToBytes(data)
JSDoc:
Helper for KDFs: consumes uint8array or string. When string is passed, does utf8 decoding, using TextDecoder.
concatBytes
Source: my-backend/node_modules/@noble/hashes/esm/utils.js
Signature: concatBytes(...arrays)
JSDoc:
Copies several Uint8Arrays into one.
createHasher
Source: my-backend/node_modules/@noble/hashes/esm/utils.js
Signature: createHasher(hashCons)
JSDoc:
For runtime check if class implements interface / export class Hash { } /* Wraps hash function, creating an interface on top of it
randomBytes
Source: my-backend/node_modules/@noble/hashes/esm/utils.js
Signature: randomBytes(bytesLength = 32)
JSDoc:
Cryptographically secure PRNG. Uses internal OS-level crypto.getRandomValues.
sha1
Source: my-backend/node_modules/@noble/hashes/legacy.js
Signature: sha1(= (0, utils_ts_1.createHasher)
JSDoc:
SHA1 (RFC 3174), MD5 (RFC 1321) and RIPEMD160 (RFC 2286) legacy, weak hash functions. Don't use them in a new protocol. What "weak" means:
- Collisions can be made with 2^18 effort in MD5, 2^60 in SHA1, 2^80 in RIPEMD160.
- No practical pre-image attacks (only theoretical, 2^123.4)
- HMAC seems kinda ok: https://datatracker.ietf.org/doc/html/rfc6151 @module / const _md_ts_1 = require("./_md.js"); const utils_ts_1 = require("./utils.js"); / Initial SHA1 state / const SHA1_IV = / @PURE / Uint32Array.from([ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0, ]); // Reusable temporary buffer const SHA1_W = / @PURE */ new Uint32Array(80); / SHA1 legacy hash class. / class SHA1 extends _md_ts_1.HashMD { constructor() { super(64, 20, 8, false); this.A = SHA1_IV0 | 0; this.B = SHA1_IV[1] | 0; this.C = SHA1_IV[2] | 0; this.D = SHA1_IV[3] | 0; this.E = SHA1_IV[4] | 0; } get() { const { A, B, C, D, E } = this; return [A, B, C, D, E]; } set(A, B, C, D, E) { this.A = A | 0; this.B = B | 0; this.C = C | 0; this.D = D | 0; this.E = E | 0; } process(view, offset) { for (let i = 0; i < 16; i++, offset += 4) SHA1_W[i] = view.getUint32(offset, false); for (let i = 16; i < 80; i++) SHA1_W[i] = (0, utils_ts_1.rotl)(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1); // Compression function main loop, 80 rounds let { A, B, C, D, E } = this; for (let i = 0; i < 80; i++) { let F, K; if (i < 20) { F = (0, _md_ts_1.Chi)(B, C, D); K = 0x5a827999; } else if (i < 40) { F = B ^ C ^ D; K = 0x6ed9eba1; } else if (i < 60) { F = (0, _md_ts_1.Maj)(B, C, D); K = 0x8f1bbcdc; } else { F = B ^ C ^ D; K = 0xca62c1d6; } const T = ((0, utils_ts_1.rotl)(A, 5) + F + E + K + SHA1_W[i]) | 0; E = D; D = C; C = (0, utils_ts_1.rotl)(B, 30); B = A; A = T; } // Add the compressed chunk to the current hash value A = (A + this.A) | 0; B = (B + this.B) | 0; C = (C + this.C) | 0; D = (D + this.D) | 0; E = (E + this.E) | 0; this.set(A, B, C, D, E); } roundClean() { (0, utils_ts_1.clean)(SHA1_W); } destroy() { this.set(0, 0, 0, 0, 0); (0, utils_ts_1.clean)(this.buffer); } } exports.SHA1 = SHA1; /* SHA1 (RFC 3174) legacy hash function. It was cryptographically broken.
md5
Source: my-backend/node_modules/@noble/hashes/legacy.js
Signature: md5(= (0, utils_ts_1.createHasher)
JSDoc:
Per-round constants / const p32 = / @PURE / Math.pow(2, 32); const K = / @PURE / Array.from({ length: 64 }, (_, i) => Math.floor(p32 * Math.abs(Math.sin(i + 1)))); / md5 initial state: same as sha1, but 4 u32 instead of 5. / const MD5_IV = / @PURE / SHA1_IV.slice(0, 4); // Reusable temporary buffer const MD5_W = / @PURE / new Uint32Array(16); / MD5 legacy hash class. */ class MD5 extends _md_ts_1.HashMD { constructor() { super(64, 16, 8, true); this.A = MD5_IV0 | 0; this.B = MD5_IV[1] | 0; this.C = MD5_IV[2] | 0; this.D = MD5_IV[3] | 0; } get() { const { A, B, C, D } = this; return [A, B, C, D]; } set(A, B, C, D) { this.A = A | 0; this.B = B | 0; this.C = C | 0; this.D = D | 0; } process(view, offset) { for (let i = 0; i < 16; i++, offset += 4) MD5_W[i] = view.getUint32(offset, true); // Compression function main loop, 64 rounds let { A, B, C, D } = this; for (let i = 0; i < 64; i++) { let F, g, s; if (i < 16) { F = (0, _md_ts_1.Chi)(B, C, D); g = i; s = [7, 12, 17, 22]; } else if (i < 32) { F = (0, _md_ts_1.Chi)(D, B, C); g = (5 * i + 1) % 16; s = [5, 9, 14, 20]; } else if (i < 48) { F = B ^ C ^ D; g = (3 * i + 5) % 16; s = [4, 11, 16, 23]; } else { F = C ^ (B | ~D); g = (7 * i) % 16; s = [6, 10, 15, 21]; } F = F + A + K[i] + MD5_W[g]; A = D; D = C; C = B; B = B + (0, utils_ts_1.rotl)(F, s[i % 4]); } // Add the compressed chunk to the current hash value A = (A + this.A) | 0; B = (B + this.B) | 0; C = (C + this.C) | 0; D = (D + this.D) | 0; this.set(A, B, C, D); } roundClean() { (0, utils_ts_1.clean)(MD5_W); } destroy() { this.set(0, 0, 0, 0); (0, utils_ts_1.clean)(this.buffer); } } exports.MD5 = MD5; / MD5 (RFC 1321) legacy hash function. It was cryptographically broken. MD5 architecture is similar to SHA1, with some differences: - Reduced output length: 16 bytes (128 bit) instead of 20 - 64 rounds, instead of 80 - Little-endian: could be faster, but will require more code - Non-linear index selection: huge speed-up for unroll - Per round constants: more memory accesses, additional speed-up for unroll
ripemd160
Source: my-backend/node_modules/@noble/hashes/legacy.js
Signature: ripemd160(= (0, utils_ts_1.createHasher)
JSDoc:
RIPEMD-160 - a legacy hash function from 1990s. * https://homes.esat.kuleuven.be/~bosselae/ripemd160.html * https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf
RIPEMD160
Source: my-backend/node_modules/@noble/hashes/ripemd160.js
Signature: RIPEMD160(= legacy_ts_1.RIPEMD160;
/** @deprecated Use import fromnoble/hashes/legacymodule */
exports.ripemd160 = legacy_ts_1.ripemd160;
//# sourceMappingURL=ripemd160.js.map)
JSDoc:
RIPEMD-160 legacy hash function.
https://homes.esat.kuleuven.be/~bosselae/ripemd160.html
https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf
@module
@deprecated
/
const legacy_ts_1 = require("./legacy.js");
/** @deprecated Use import from noble/hashes/legacy module
SHA1
Source: my-backend/node_modules/@noble/hashes/sha1.js
Signature: SHA1(= legacy_ts_1.SHA1;
/** @deprecated Use import fromnoble/hashes/legacymodule */
exports.sha1 = legacy_ts_1.sha1;
//# sourceMappingURL=sha1.js.map)
JSDoc:
SHA1 (RFC 3174) legacy hash function.
@module
@deprecated
/
const legacy_ts_1 = require("./legacy.js");
/** @deprecated Use import from noble/hashes/legacy module
sha256
Source: my-backend/node_modules/@noble/hashes/sha2.js
Signature: sha256(= (0, utils_ts_1.createHasher)
JSDoc:
SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.
SHA256 is the fastest hash implementable in JS, even faster than Blake3.
Check out RFC 4634 and
FIPS 180-4.
@module
/
const _md_ts_1 = require("./_md.js");
const u64 = require("./_u64.js");
const utils_ts_1 = require("./utils.js");
/
Round constants:
First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)
/
// prettier-ignore
const SHA256_K = / @PURE / Uint32Array.from([
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
]);
/ Reusable temporary buffer. "W" comes straight from spec. /
const SHA256_W = / @PURE / new Uint32Array(64);
class SHA256 extends _md_ts_1.HashMD {
constructor(outputLen = 32) {
super(64, outputLen, 8, false);
// We cannot use array here since array allows indexing by variable
// which means optimizer/compiler cannot use registers.
this.A = _md_ts_1.SHA256_IV0 | 0;
this.B = _md_ts_1.SHA256_IV[1] | 0;
this.C = _md_ts_1.SHA256_IV[2] | 0;
this.D = _md_ts_1.SHA256_IV[3] | 0;
this.E = _md_ts_1.SHA256_IV[4] | 0;
this.F = _md_ts_1.SHA256_IV[5] | 0;
this.G = _md_ts_1.SHA256_IV[6] | 0;
this.H = _md_ts_1.SHA256_IV[7] | 0;
}
get() {
const { A, B, C, D, E, F, G, H } = this;
return [A, B, C, D, E, F, G, H];
}
// prettier-ignore
set(A, B, C, D, E, F, G, H) {
this.A = A | 0;
this.B = B | 0;
this.C = C | 0;
this.D = D | 0;
this.E = E | 0;
this.F = F | 0;
this.G = G | 0;
this.H = H | 0;
}
process(view, offset) {
// Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array
for (let i = 0; i < 16; i++, offset += 4)
SHA256_W[i] = view.getUint32(offset, false);
for (let i = 16; i < 64; i++) {
const W15 = SHA256_W[i - 15];
const W2 = SHA256_W[i - 2];
const s0 = (0, utils_ts_1.rotr)(W15, 7) ^ (0, utils_ts_1.rotr)(W15, 18) ^ (W15 >>> 3);
const s1 = (0, utils_ts_1.rotr)(W2, 17) ^ (0, utils_ts_1.rotr)(W2, 19) ^ (W2 >>> 10);
SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;
}
// Compression function main loop, 64 rounds
let { A, B, C, D, E, F, G, H } = this;
for (let i = 0; i < 64; i++) {
const sigma1 = (0, utils_ts_1.rotr)(E, 6) ^ (0, utils_ts_1.rotr)(E, 11) ^ (0, utils_ts_1.rotr)(E, 25);
const T1 = (H + sigma1 + (0, _md_ts_1.Chi)(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
const sigma0 = (0, utils_ts_1.rotr)(A, 2) ^ (0, utils_ts_1.rotr)(A, 13) ^ (0, utils_ts_1.rotr)(A, 22);
const T2 = (sigma0 + (0, _md_ts_1.Maj)(A, B, C)) | 0;
H = G;
G = F;
F = E;
E = (D + T1) | 0;
D = C;
C = B;
B = A;
A = (T1 + T2) | 0;
}
// Add the compressed chunk to the current hash value
A = (A + this.A) | 0;
B = (B + this.B) | 0;
C = (C + this.C) | 0;
D = (D + this.D) | 0;
E = (E + this.E) | 0;
F = (F + this.F) | 0;
G = (G + this.G) | 0;
H = (H + this.H) | 0;
this.set(A, B, C, D, E, F, G, H);
}
roundClean() {
(0, utils_ts_1.clean)(SHA256_W);
}
destroy() {
this.set(0, 0, 0, 0, 0, 0, 0, 0);
(0, utils_ts_1.clean)(this.buffer);
}
}
exports.SHA256 = SHA256;
class SHA224 extends SHA256 {
constructor() {
super(28);
this.A = _md_ts_1.SHA224_IV0 | 0;
this.B = _md_ts_1.SHA224_IV[1] | 0;
this.C = _md_ts_1.SHA224_IV[2] | 0;
this.D = _md_ts_1.SHA224_IV[3] | 0;
this.E = _md_ts_1.SHA224_IV[4] | 0;
this.F = _md_ts_1.SHA224_IV[5] | 0;
this.G = _md_ts_1.SHA224_IV[6] | 0;
this.H = _md_ts_1.SHA224_IV[7] | 0;
}
}
exports.SHA224 = SHA224;
// SHA2-512 is slower than sha256 in js because u64 operations are slow.
// Round contants
// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409
// prettier-ignore
const K512 = / @PURE / (() => u64.split([
'0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',
'0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',
'0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',
'0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',
'0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',
'0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',
'0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',
'0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',
'0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',
'0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',
'0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',
'0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',
'0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',
'0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',
'0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',
'0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',
'0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',
'0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',
'0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',
'0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'
].map(n => BigInt(n))))();
const SHA512_Kh = / @PURE / (() => K5120)();
const SHA512_Kl = / @PURE / (() => K512[1])();
// Reusable temporary buffers
const SHA512_W_H = / @PURE / new Uint32Array(80);
const SHA512_W_L = / @PURE / new Uint32Array(80);
class SHA512 extends _md_ts_1.HashMD {
constructor(outputLen = 64) {
super(128, outputLen, 16, false);
// We cannot use array here since array allows indexing by variable
// which means optimizer/compiler cannot use registers.
// h -- high 32 bits, l -- low 32 bits
this.Ah = _md_ts_1.SHA512_IV0 | 0;
this.Al = _md_ts_1.SHA512_IV[1] | 0;
this.Bh = _md_ts_1.SHA512_IV[2] | 0;
this.Bl = _md_ts_1.SHA512_IV[3] | 0;
this.Ch = _md_ts_1.SHA512_IV[4] | 0;
this.Cl = _md_ts_1.SHA512_IV[5] | 0;
this.Dh = _md_ts_1.SHA512_IV[6] | 0;
this.Dl = _md_ts_1.SHA512_IV[7] | 0;
this.Eh = _md_ts_1.SHA512_IV[8] | 0;
this.El = _md_ts_1.SHA512_IV[9] | 0;
this.Fh = _md_ts_1.SHA512_IV[10] | 0;
this.Fl = _md_ts_1.SHA512_IV[11] | 0;
this.Gh = _md_ts_1.SHA512_IV[12] | 0;
this.Gl = _md_ts_1.SHA512_IV[13] | 0;
this.Hh = _md_ts_1.SHA512_IV[14] | 0;
this.Hl = _md_ts_1.SHA512_IV[15] | 0;
}
// prettier-ignore
get() {
const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
}
// prettier-ignore
set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
this.Ah = Ah | 0;
this.Al = Al | 0;
this.Bh = Bh | 0;
this.Bl = Bl | 0;
this.Ch = Ch | 0;
this.Cl = Cl | 0;
this.Dh = Dh | 0;
this.Dl = Dl | 0;
this.Eh = Eh | 0;
this.El = El | 0;
this.Fh = Fh | 0;
this.Fl = Fl | 0;
this.Gh = Gh | 0;
this.Gl = Gl | 0;
this.Hh = Hh | 0;
this.Hl = Hl | 0;
}
process(view, offset) {
// Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array
for (let i = 0; i < 16; i++, offset += 4) {
SHA512_W_H[i] = view.getUint32(offset);
SHA512_W_L[i] = view.getUint32((offset += 4));
}
for (let i = 16; i < 80; i++) {
// s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)
const W15h = SHA512_W_H[i - 15] | 0;
const W15l = SHA512_W_L[i - 15] | 0;
const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);
const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);
// s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)
const W2h = SHA512_W_H[i - 2] | 0;
const W2l = SHA512_W_L[i - 2] | 0;
const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);
const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);
// SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];
const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
SHA512_W_H[i] = SUMh | 0;
SHA512_W_L[i] = SUMl | 0;
}
let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
// Compression function main loop, 80 rounds
for (let i = 0; i < 80; i++) {
// S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)
const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);
const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);
//const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
const CHIh = (Eh & Fh) ^ (~Eh & Gh);
const CHIl = (El & Fl) ^ (~El & Gl);
// T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]
// prettier-ignore
const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
const T1l = T1ll | 0;
// S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)
const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);
const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);
const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);
const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);
Hh = Gh | 0;
Hl = Gl | 0;
Gh = Fh | 0;
Gl = Fl | 0;
Fh = Eh | 0;
Fl = El | 0;
({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
Dh = Ch | 0;
Dl = Cl | 0;
Ch = Bh | 0;
Cl = Bl | 0;
Bh = Ah | 0;
Bl = Al | 0;
const All = u64.add3L(T1l, sigma0l, MAJl);
Ah = u64.add3H(All, T1h, sigma0h, MAJh);
Al = All | 0;
}
// Add the compressed chunk to the current hash value
({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
}
roundClean() {
(0, utils_ts_1.clean)(SHA512_W_H, SHA512_W_L);
}
destroy() {
(0, utils_ts_1.clean)(this.buffer);
this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
}
exports.SHA512 = SHA512;
class SHA384 extends SHA512 {
constructor() {
super(48);
this.Ah = _md_ts_1.SHA384_IV0 | 0;
this.Al = _md_ts_1.SHA384_IV[1] | 0;
this.Bh = _md_ts_1.SHA384_IV[2] | 0;
this.Bl = _md_ts_1.SHA384_IV[3] | 0;
this.Ch = _md_ts_1.SHA384_IV[4] | 0;
this.Cl = _md_ts_1.SHA384_IV[5] | 0;
this.Dh = _md_ts_1.SHA384_IV[6] | 0;
this.Dl = _md_ts_1.SHA384_IV[7] | 0;
this.Eh = _md_ts_1.SHA384_IV[8] | 0;
this.El = _md_ts_1.SHA384_IV[9] | 0;
this.Fh = _md_ts_1.SHA384_IV[10] | 0;
this.Fl = _md_ts_1.SHA384_IV[11] | 0;
this.Gh = _md_ts_1.SHA384_IV[12] | 0;
this.Gl = _md_ts_1.SHA384_IV[13] | 0;
this.Hh = _md_ts_1.SHA384_IV[14] | 0;
this.Hl = _md_ts_1.SHA384_IV[15] | 0;
}
}
exports.SHA384 = SHA384;
/
Truncated SHA512/256 and SHA512/224.
SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as "intermediary" IV of SHA512/t.
Then t hashes string to produce result IV.
See test/misc/sha2-gen-iv.js.
/
/ SHA512/224 IV /
const T224_IV = / @PURE / Uint32Array.from([
0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,
0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,
]);
/ SHA512/256 IV /
const T256_IV = / @PURE */ Uint32Array.from([
0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,
0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,
]);
class SHA512_224 extends SHA512 {
constructor() {
super(28);
this.Ah = T224_IV0 | 0;
this.Al = T224_IV[1] | 0;
this.Bh = T224_IV[2] | 0;
this.Bl = T224_IV[3] | 0;
this.Ch = T224_IV[4] | 0;
this.Cl = T224_IV[5] | 0;
this.Dh = T224_IV[6] | 0;
this.Dl = T224_IV[7] | 0;
this.Eh = T224_IV[8] | 0;
this.El = T224_IV[9] | 0;
this.Fh = T224_IV[10] | 0;
this.Fl = T224_IV[11] | 0;
this.Gh = T224_IV[12] | 0;
this.Gl = T224_IV[13] | 0;
this.Hh = T224_IV[14] | 0;
this.Hl = T224_IV[15] | 0;
}
}
exports.SHA512_224 = SHA512_224;
class SHA512_256 extends SHA512 {
constructor() {
super(32);
this.Ah = T256_IV0 | 0;
this.Al = T256_IV[1] | 0;
this.Bh = T256_IV[2] | 0;
this.Bl = T256_IV[3] | 0;
this.Ch = T256_IV[4] | 0;
this.Cl = T256_IV[5] | 0;
this.Dh = T256_IV[6] | 0;
this.Dl = T256_IV[7] | 0;
this.Eh = T256_IV[8] | 0;
this.El = T256_IV[9] | 0;
this.Fh = T256_IV[10] | 0;
this.Fl = T256_IV[11] | 0;
this.Gh = T256_IV[12] | 0;
this.Gl = T256_IV[13] | 0;
this.Hh = T256_IV[14] | 0;
this.Hl = T256_IV[15] | 0;
}
}
exports.SHA512_256 = SHA512_256;
/
SHA2-256 hash function from RFC 4634.
It is the fastest JS hash, even faster than Blake3. To break sha256 using birthday attack, attackers need to try 2^128 hashes. BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
sha224
Source: my-backend/node_modules/@noble/hashes/sha2.js
Signature: sha224(= (0, utils_ts_1.createHasher)
JSDoc:
SHA2-224 hash function from RFC 4634
sha512
Source: my-backend/node_modules/@noble/hashes/sha2.js
Signature: sha512(= (0, utils_ts_1.createHasher)
JSDoc:
SHA2-512 hash function from RFC 4634.
sha384
Source: my-backend/node_modules/@noble/hashes/sha2.js
Signature: sha384(= (0, utils_ts_1.createHasher)
JSDoc:
SHA2-384 hash function from RFC 4634.
sha512_256
Source: my-backend/node_modules/@noble/hashes/sha2.js
Signature: sha512_256(= (0, utils_ts_1.createHasher)
JSDoc:
SHA2-512/256 "truncated" hash function, with improved resistance to length extension attacks. See the paper on truncated SHA512.
sha512_224
Source: my-backend/node_modules/@noble/hashes/sha2.js
Signature: sha512_224(= (0, utils_ts_1.createHasher)
JSDoc:
SHA2-512/224 "truncated" hash function, with improved resistance to length extension attacks. See the paper on truncated SHA512.
SHA256
Source: my-backend/node_modules/@noble/hashes/sha256.js
Signature: SHA256(= sha2_ts_1.SHA256;
/** @deprecated Use import fromnoble/hashes/sha2module */
exports.sha256 = sha2_ts_1.sha256;
/** @deprecated Use import fromnoble/hashes/sha2module */
exports.SHA224 = sha2_ts_1.SHA224;
/** @deprecated Use import fromnoble/hashes/sha2module */
exports.sha224 = sha2_ts_1.sha224;
//# sourceMappingURL=sha256.js.map)
JSDoc:
SHA2-256 a.k.a. sha256. In JS, it is the fastest hash, even faster than Blake3.
To break sha256 using birthday attack, attackers need to try 2^128 hashes. BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
Check out FIPS 180-4.
@module
@deprecated
/
const sha2_ts_1 = require("./sha2.js");
/** @deprecated Use import from noble/hashes/sha2 module
tuplehash128
Source: my-backend/node_modules/@noble/hashes/sha3-addons.js
Signature: tuplehash128(= (()
JSDoc:
SHA3 (keccak) addons.
- Full NIST SP 800-185: cSHAKE, KMAC, TupleHash, ParallelHash + XOF variants
- Reduced-round Keccak (draft):
- 🦘 K12 aka KangarooTwelve
- M14 aka MarsupilamiFourteen
- TurboSHAKE
- KeccakPRG: Pseudo-random generator based on Keccak (pdf) @module / const sha3_ts_1 = require("./sha3.js"); const utils_ts_1 = require("./utils.js"); // cSHAKE && KMAC (NIST SP800-185) const _8n = BigInt(8); const _ffn = BigInt(0xff); // NOTE: it is safe to use bigints here, since they used only for length encoding (not actual data). // We use bigints in sha256 for lengths too. function leftEncode(n) { n = BigInt(n); const res = [Number(n & _ffn)]; n >>= _8n; for (; n > 0; n >>= _8n) res.unshift(Number(n & _ffn)); res.unshift(res.length); return new Uint8Array(res); } function rightEncode(n) { n = BigInt(n); const res = [Number(n & _ffn)]; n >>= _8n; for (; n > 0; n >>= _8n) res.unshift(Number(n & _ffn)); res.push(res.length); return new Uint8Array(res); } function chooseLen(opts, outputLen) { return opts.dkLen === undefined ? outputLen : opts.dkLen; } const abytesOrZero = (buf) => { if (buf === undefined) return Uint8Array.of(); return (0, utils_ts_1.toBytes)(buf); }; // NOTE: second modulo is necessary since we don't need to add padding if current element takes whole block const getPadding = (len, block) => new Uint8Array((block - (len % block)) % block); // Personalization function cshakePers(hash, opts = {}) { if (!opts || (!opts.personalization && !opts.NISTfn)) return hash; // Encode and pad inplace to avoid unneccesary memory copies/slices (so we don't need to zero them later) // bytepad(encode_string(N) || encode_string(S), 168) const blockLenBytes = leftEncode(hash.blockLen); const fn = abytesOrZero(opts.NISTfn); const fnLen = leftEncode(_8n * BigInt(fn.length)); // length in bits const pers = abytesOrZero(opts.personalization); const persLen = leftEncode(_8n * BigInt(pers.length)); // length in bits if (!fn.length && !pers.length) return hash; hash.suffix = 0x04; hash.update(blockLenBytes).update(fnLen).update(fn).update(persLen).update(pers); let totalLen = blockLenBytes.length + fnLen.length + fn.length + persLen.length + pers.length; hash.update(getPadding(totalLen, hash.blockLen)); return hash; } const gencShake = (suffix, blockLen, outputLen) => (0, utils_ts_1.createXOFer)((opts = {}) => cshakePers(new sha3_ts_1.Keccak(blockLen, suffix, chooseLen(opts, outputLen), true), opts)); exports.cshake128 = (() => gencShake(0x1f, 168, 128 / 8))(); exports.cshake256 = (() => gencShake(0x1f, 136, 256 / 8))(); class KMAC extends sha3_ts_1.Keccak { constructor(blockLen, outputLen, enableXOF, key, opts = {}) { super(blockLen, 0x1f, outputLen, enableXOF); cshakePers(this, { NISTfn: 'KMAC', personalization: opts.personalization }); key = (0, utils_ts_1.toBytes)(key); (0, utils_ts_1.abytes)(key); // 1. newX = bytepad(encode_string(K), 168) || X || right_encode(L). const blockLenBytes = leftEncode(this.blockLen); const keyLen = leftEncode(_8n * BigInt(key.length)); this.update(blockLenBytes).update(keyLen).update(key); const totalLen = blockLenBytes.length + keyLen.length + key.length; this.update(getPadding(totalLen, this.blockLen)); } finish() { if (!this.finished) this.update(rightEncode(this.enableXOF ? 0 : _8n * BigInt(this.outputLen))); // outputLen in bits super.finish(); } _cloneInto(to) { // Create new instance without calling constructor since key already in state and we don't know it. // Force "to" to be instance of KMAC instead of Sha3. if (!to) { to = Object.create(Object.getPrototypeOf(this), {}); to.state = this.state.slice(); to.blockLen = this.blockLen; to.state32 = (0, utils_ts_1.u32)(to.state); } return super._cloneInto(to); } clone() { return this._cloneInto(); } } exports.KMAC = KMAC; function genKmac(blockLen, outputLen, xof = false) { const kmac = (key, message, opts) => kmac.create(key, opts).update(message).digest(); kmac.create = (key, opts = {}) => new KMAC(blockLen, chooseLen(opts, outputLen), xof, key, opts); return kmac; } exports.kmac128 = (() => genKmac(168, 128 / 8))(); exports.kmac256 = (() => genKmac(136, 256 / 8))(); exports.kmac128xof = (() => genKmac(168, 128 / 8, true))(); exports.kmac256xof = (() => genKmac(136, 256 / 8, true))(); // TupleHash // Usage: tuple(['ab', 'cd']) != tuple(['a', 'bcd']) class TupleHash extends sha3_ts_1.Keccak { constructor(blockLen, outputLen, enableXOF, opts = {}) { super(blockLen, 0x1f, outputLen, enableXOF); cshakePers(this, { NISTfn: 'TupleHash', personalization: opts.personalization }); // Change update after cshake processed this.update = (data) => { data = (0, utils_ts_1.toBytes)(data); (0, utils_ts_1.abytes)(data); super.update(leftEncode(_8n * BigInt(data.length))); super.update(data); return this; }; } finish() { if (!this.finished) super.update(rightEncode(this.enableXOF ? 0 : _8n * BigInt(this.outputLen))); // outputLen in bits super.finish(); } _cloneInto(to) { to || (to = new TupleHash(this.blockLen, this.outputLen, this.enableXOF)); return super._cloneInto(to); } clone() { return this._cloneInto(); } } exports.TupleHash = TupleHash; function genTuple(blockLen, outputLen, xof = false) { const tuple = (messages, opts) => { const h = tuple.create(opts); for (const msg of messages) h.update(msg); return h.digest(); }; tuple.create = (opts = {}) => new TupleHash(blockLen, chooseLen(opts, outputLen), xof, opts); return tuple; } /** 128-bit TupleHASH.
tuplehash256
Source: my-backend/node_modules/@noble/hashes/sha3-addons.js
Signature: tuplehash256(= (()
JSDoc:
256-bit TupleHASH.
tuplehash128xof
Source: my-backend/node_modules/@noble/hashes/sha3-addons.js
Signature: tuplehash128xof(= (()
JSDoc:
128-bit TupleHASH XOF.
tuplehash256xof
Source: my-backend/node_modules/@noble/hashes/sha3-addons.js
Signature: tuplehash256xof(= (()
JSDoc:
256-bit TupleHASH XOF.
parallelhash128
Source: my-backend/node_modules/@noble/hashes/sha3-addons.js
Signature: parallelhash128(= (()
JSDoc:
128-bit ParallelHash. In JS, it is not parallel.
parallelhash256
Source: my-backend/node_modules/@noble/hashes/sha3-addons.js
Signature: parallelhash256(= (()
JSDoc:
256-bit ParallelHash. In JS, it is not parallel.
parallelhash128xof
Source: my-backend/node_modules/@noble/hashes/sha3-addons.js
Signature: parallelhash128xof(= (()
JSDoc:
128-bit ParallelHash XOF. In JS, it is not parallel.
parallelhash256xof
Source: my-backend/node_modules/@noble/hashes/sha3-addons.js
Signature: parallelhash256xof(= (()
JSDoc:
256-bit ParallelHash. In JS, it is not parallel.
turboshake128
Source: my-backend/node_modules/@noble/hashes/sha3-addons.js
Signature: turboshake128(= genTurboshake(168, 256 / 8)
JSDoc:
TurboSHAKE 128-bit: reduced 12-round keccak.
turboshake256
Source: my-backend/node_modules/@noble/hashes/sha3-addons.js
Signature: turboshake256(= genTurboshake(136, 512 / 8)
JSDoc:
TurboSHAKE 256-bit: reduced 12-round keccak.
k12
Source: my-backend/node_modules/@noble/hashes/sha3-addons.js
Signature: k12(= (()
JSDoc:
KangarooTwelve: reduced 12-round keccak.
m14
Source: my-backend/node_modules/@noble/hashes/sha3-addons.js
Signature: m14(= (()
JSDoc:
MarsupilamiFourteen: reduced 14-round keccak.
sha3_224
Source: my-backend/node_modules/@noble/hashes/sha3.js
Signature: sha3_224(= (()
JSDoc:
SHA3 (keccak) hash function, based on a new "Sponge function" design. Different from older hashes, the internal state is bigger than output size.
Check out FIPS-202, Website, the differences between SHA-3 and Keccak.
Check out sha3-addons module for cSHAKE, k12, and others.
@module
/
const _u64_ts_1 = require("./_u64.js");
// prettier-ignore
const utils_ts_1 = require("./utils.js");
// No PURE annotations in sha3 header:
// EVERYTHING is in fact used on every export.
// Various per round constants calculations
const _0n = BigInt(0);
const _1n = BigInt(1);
const _2n = BigInt(2);
const _7n = BigInt(7);
const _256n = BigInt(256);
const _0x71n = BigInt(0x71);
const SHA3_PI = [];
const SHA3_ROTL = [];
const _SHA3_IOTA = [];
for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {
// Pi
[x, y] = [y, (2 * x + 3 * y) % 5];
SHA3_PI.push(2 * (5 * y + x));
// Rotational
SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);
// Iota
let t = _0n;
for (let j = 0; j < 7; j++) {
R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n;
if (R & _2n)
t ^= _1n << ((_1n << / @PURE / BigInt(j)) - _1n);
}
_SHA3_IOTA.push(t);
}
const IOTAS = (0, _u64_ts_1.split)(_SHA3_IOTA, true);
const SHA3_IOTA_H = IOTAS0;
const SHA3_IOTA_L = IOTAS[1];
// Left rotation (without 0, 32, 64)
const rotlH = (h, l, s) => (s > 32 ? (0, _u64_ts_1.rotlBH)(h, l, s) : (0, _u64_ts_1.rotlSH)(h, l, s));
const rotlL = (h, l, s) => (s > 32 ? (0, _u64_ts_1.rotlBL)(h, l, s) : (0, _u64_ts_1.rotlSL)(h, l, s));
/ keccakf1600 internal function, additionally allows to adjust round count. */
function keccakP(s, rounds = 24) {
const B = new Uint32Array(5 * 2);
// NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)
for (let round = 24 - rounds; round < 24; round++) {
// Theta θ
for (let x = 0; x < 10; x++)
B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];
for (let x = 0; x < 10; x += 2) {
const idx1 = (x + 8) % 10;
const idx0 = (x + 2) % 10;
const B0 = B[idx0];
const B1 = B[idx0 + 1];
const Th = rotlH(B0, B1, 1) ^ B[idx1];
const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];
for (let y = 0; y < 50; y += 10) {
s[x + y] ^= Th;
s[x + y + 1] ^= Tl;
}
}
// Rho (ρ) and Pi (π)
let curH = s[2];
let curL = s[3];
for (let t = 0; t < 24; t++) {
const shift = SHA3_ROTL[t];
const Th = rotlH(curH, curL, shift);
const Tl = rotlL(curH, curL, shift);
const PI = SHA3_PI[t];
curH = s[PI];
curL = s[PI + 1];
s[PI] = Th;
s[PI + 1] = Tl;
}
// Chi (χ)
for (let y = 0; y < 50; y += 10) {
for (let x = 0; x < 10; x++)
B[x] = s[y + x];
for (let x = 0; x < 10; x++)
s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];
}
// Iota (ι)
s0 ^= SHA3_IOTA_H[round];
s[1] ^= SHA3_IOTA_L[round];
}
(0, utils_ts_1.clean)(B);
}
/ Keccak sponge function. /
class Keccak extends utils_ts_1.Hash {
// NOTE: we accept arguments in bytes instead of bits here.
constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
super();
this.pos = 0;
this.posOut = 0;
this.finished = false;
this.destroyed = false;
this.enableXOF = false;
this.blockLen = blockLen;
this.suffix = suffix;
this.outputLen = outputLen;
this.enableXOF = enableXOF;
this.rounds = rounds;
// Can be passed from user as dkLen
(0, utils_ts_1.anumber)(outputLen);
// 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes
// 0 < blockLen < 200
if (!(0 < blockLen && blockLen < 200))
throw new Error('only keccak-f1600 function is supported');
this.state = new Uint8Array(200);
this.state32 = (0, utils_ts_1.u32)(this.state);
}
clone() {
return this._cloneInto();
}
keccak() {
(0, utils_ts_1.swap32IfBE)(this.state32);
keccakP(this.state32, this.rounds);
(0, utils_ts_1.swap32IfBE)(this.state32);
this.posOut = 0;
this.pos = 0;
}
update(data) {
(0, utils_ts_1.aexists)(this);
data = (0, utils_ts_1.toBytes)(data);
(0, utils_ts_1.abytes)(data);
const { blockLen, state } = this;
const len = data.length;
for (let pos = 0; pos < len;) {
const take = Math.min(blockLen - this.pos, len - pos);
for (let i = 0; i < take; i++)
state[this.pos++] ^= data[pos++];
if (this.pos === blockLen)
this.keccak();
}
return this;
}
finish() {
if (this.finished)
return;
this.finished = true;
const { state, suffix, pos, blockLen } = this;
// Do the padding
state[pos] ^= suffix;
if ((suffix & 0x80) !== 0 && pos === blockLen - 1)
this.keccak();
state[blockLen - 1] ^= 0x80;
this.keccak();
}
writeInto(out) {
(0, utils_ts_1.aexists)(this, false);
(0, utils_ts_1.abytes)(out);
this.finish();
const bufferOut = this.state;
const { blockLen } = this;
for (let pos = 0, len = out.length; pos < len;) {
if (this.posOut >= blockLen)
this.keccak();
const take = Math.min(blockLen - this.posOut, len - pos);
out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
this.posOut += take;
pos += take;
}
return out;
}
xofInto(out) {
// Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF
if (!this.enableXOF)
throw new Error('XOF is not possible for this instance');
return this.writeInto(out);
}
xof(bytes) {
(0, utils_ts_1.anumber)(bytes);
return this.xofInto(new Uint8Array(bytes));
}
digestInto(out) {
(0, utils_ts_1.aoutput)(out, this);
if (this.finished)
throw new Error('digest() was already called');
this.writeInto(out);
this.destroy();
return out;
}
digest() {
return this.digestInto(new Uint8Array(this.outputLen));
}
destroy() {
this.destroyed = true;
(0, utils_ts_1.clean)(this.state);
}
_cloneInto(to) {
const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds));
to.state32.set(this.state32);
to.pos = this.pos;
to.posOut = this.posOut;
to.finished = this.finished;
to.rounds = rounds;
// Suffix can change in cSHAKE
to.suffix = suffix;
to.outputLen = outputLen;
to.enableXOF = enableXOF;
to.destroyed = this.destroyed;
return to;
}
}
exports.Keccak = Keccak;
const gen = (suffix, blockLen, outputLen) => (0, utils_ts_1.createHasher)(() => new Keccak(blockLen, suffix, outputLen));
/* SHA3-224 hash function.
sha3_256
Source: my-backend/node_modules/@noble/hashes/sha3.js
Signature: sha3_256(= (()
JSDoc:
SHA3-256 hash function. Different from keccak-256.
sha3_384
Source: my-backend/node_modules/@noble/hashes/sha3.js
Signature: sha3_384(= (()
JSDoc:
SHA3-384 hash function.
sha3_512
Source: my-backend/node_modules/@noble/hashes/sha3.js
Signature: sha3_512(= (()
JSDoc:
SHA3-512 hash function.
keccak_224
Source: my-backend/node_modules/@noble/hashes/sha3.js
Signature: keccak_224(= (()
JSDoc:
keccak-224 hash function.
keccak_256
Source: my-backend/node_modules/@noble/hashes/sha3.js
Signature: keccak_256(= (()
JSDoc:
keccak-256 hash function. Different from SHA3-256.
keccak_384
Source: my-backend/node_modules/@noble/hashes/sha3.js
Signature: keccak_384(= (()
JSDoc:
keccak-384 hash function.
keccak_512
Source: my-backend/node_modules/@noble/hashes/sha3.js
Signature: keccak_512(= (()
JSDoc:
keccak-512 hash function.
shake128
Source: my-backend/node_modules/@noble/hashes/sha3.js
Signature: shake128(= (()
JSDoc:
SHAKE128 XOF with 128-bit security.
shake256
Source: my-backend/node_modules/@noble/hashes/sha3.js
Signature: shake256(= (()
JSDoc:
SHAKE256 XOF with 256-bit security.
SHA512
Source: my-backend/node_modules/@noble/hashes/sha512.js
Signature: SHA512(= sha2_ts_1.SHA512;
/** @deprecated Use import fromnoble/hashes/sha2module */
exports.sha512 = sha2_ts_1.sha512;
/** @deprecated Use import fromnoble/hashes/sha2module */
exports.SHA384 = sha2_ts_1.SHA384;
/** @deprecated Use import fromnoble/hashes/sha2module */
exports.sha384 = sha2_ts_1.sha384;
/** @deprecated Use import fromnoble/hashes/sha2module */
exports.SHA512_224 = sha2_ts_1.SHA512_224;
/** @deprecated Use import fromnoble/hashes/sha2module */
exports.sha512_224 = sha2_ts_1.sha512_224;
/** @deprecated Use import fromnoble/hashes/sha2module */
exports.SHA512_256 = sha2_ts_1.SHA512_256;
/** @deprecated Use import fromnoble/hashes/sha2module */
exports.sha512_256 = sha2_ts_1.sha512_256;
//# sourceMappingURL=sha512.js.map)
JSDoc:
SHA2-512 a.k.a. sha512 and sha384. It is slower than sha256 in js because u64 operations are slow.
Check out RFC 4634 and
the paper on truncated SHA512/256.
@module
@deprecated
/
const sha2_ts_1 = require("./sha2.js");
/** @deprecated Use import from noble/hashes/sha2 module
setBigUint64
Source: my-backend/node_modules/@noble/hashes/src/_md.ts
Signature: setBigUint64(
view: DataView,
byteOffset: number,
value: bigint,
isLE: boolean
)
JSDoc:
Internal Merkle-Damgard hash utils. @module / import { type Input, Hash, abytes, aexists, aoutput, clean, createView, toBytes } from './utils.ts';
/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64
Chi
Source: my-backend/node_modules/@noble/hashes/src/_md.ts
Signature: Chi(a: number, b: number, c: number)
JSDoc:
Choice: a ? b : c
Maj
Source: my-backend/node_modules/@noble/hashes/src/_md.ts
Signature: Maj(a: number, b: number, c: number)
JSDoc:
Majority function, true if any two inputs is true.
deriveMainSeed
Source: my-backend/node_modules/@noble/hashes/src/eskdf.ts
Signature: deriveMainSeed(username: string, password: string)
JSDoc:
Experimental KDF for AES. / import { hkdf } from './hkdf.ts'; import { pbkdf2 as _pbkdf2 } from './pbkdf2.ts'; import { scrypt as _scrypt } from './scrypt.ts'; import { sha256 } from './sha256.ts'; import { abytes, bytesToHex, clean, createView, hexToBytes, kdfInputToBytes } from './utils.ts';
// A tiny KDF for various applications like AES key-gen. // Uses HKDF in a non-standard way, so it's not "KDF-secure", only "PRF-secure". // Which is good enough: assume sha2-256 retained preimage resistance.
const SCRYPT_FACTOR = 2 ** 19; const PBKDF2_FACTOR = 2 ** 17;
// Scrypt KDF export function scrypt(password: string, salt: string): Uint8Array { return _scrypt(password, salt, { N: SCRYPT_FACTOR, r: 8, p: 1, dkLen: 32 }); }
// PBKDF2-HMAC-SHA256 export function pbkdf2(password: string, salt: string): Uint8Array { return _pbkdf2(sha256, password, salt, { c: PBKDF2_FACTOR, dkLen: 32 }); }
// Combines two 32-byte byte arrays function xor32(a: Uint8Array, b: Uint8Array): Uint8Array { abytes(a, 32); abytes(b, 32); const arr = new Uint8Array(32); for (let i = 0; i < 32; i++) { arr[i] = a[i] ^ b[i]; } return arr; }
function strHasLength(str: string, min: number, max: number): boolean { return typeof str === 'string' && str.length >= min && str.length <= max; }
/**
Derives main seed. Takes a lot of time. Prefer eskdf method instead.
extract
Source: my-backend/node_modules/@noble/hashes/src/hkdf.ts
Signature: extract(hash: CHash, ikm: Input, salt?: Input)
JSDoc:
HKDF (RFC 5869): extract + expand in one step. See https://soatok.blog/2021/11/17/understanding-hkdf/. @module / import { hmac } from './hmac.ts'; import { ahash, anumber, type CHash, clean, type Input, toBytes } from './utils.ts';
/**
HKDF-extract from spec. Less important part. HKDF-Extract(IKM, salt) -> PRK
Arguments position differs from spec (IKM is first one, since it is not optional)
@param hash - hash function that would be used (e.g. sha256)
@param ikm - input keying material, the initial key
@param salt - optional salt value (a non-secret random value)
expand
Source: my-backend/node_modules/@noble/hashes/src/hkdf.ts
Signature: expand(hash: CHash, prk: Input, info?: Input, length: number = 32)
JSDoc:
HKDF-expand from the spec. The most important part. HKDF-Expand(PRK, info, L) -> OKM
@param hash - hash function that would be used (e.g. sha256)
@param prk - a pseudorandom key of at least HashLen octets (usually, the output from the extract step)
@param info - optional context and application specific information (can be a zero-length string)
@param length - length of output keying material in bytes
pbkdf2
Source: my-backend/node_modules/@noble/hashes/src/pbkdf2.ts
Signature: pbkdf2(
hash: CHash,
password: KDFInput,
salt: KDFInput,
opts: Pbkdf2Opt
)
JSDoc:
PBKDF (RFC 2898). Can be used to create a key from password and salt. @module / import { hmac } from './hmac.ts'; // prettier-ignore import { ahash, anumber, asyncLoop, checkOpts, clean, createView, Hash, kdfInputToBytes, type CHash, type KDFInput } from './utils.ts';
export type Pbkdf2Opt = { c: number; // Iterations dkLen?: number; // Desired key length in bytes (Intended output length in octets of the derived key asyncTick?: number; // Maximum time in ms for which async function can block execution }; // Common prologue and epilogue for sync/async functions function pbkdf2Init(hash: CHash, _password: KDFInput, _salt: KDFInput, _opts: Pbkdf2Opt) { ahash(hash); const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts); const { c, dkLen, asyncTick } = opts; anumber(c); anumber(dkLen); anumber(asyncTick); if (c < 1) throw new Error('iterations (c) should be >= 1'); const password = kdfInputToBytes(_password); const salt = kdfInputToBytes(_salt); // DK = PBKDF2(PRF, Password, Salt, c, dkLen); const DK = new Uint8Array(dkLen); // U1 = PRF(Password, Salt + INT_32_BE(i)) const PRF = hmac.create(hash, password); const PRFSalt = PRF._cloneInto().update(salt); return { c, dkLen, asyncTick, DK, PRF, PRFSalt }; }
function pbkdf2Output
/** PBKDF2-HMAC: RFC 2898 key derivation function @param hash - hash function that would be used e.g. sha256 @param password - password from which a derived key is generated @param salt - cryptographic salt @param opts - {c, dkLen} where c is work factor and dkLen is output message size @example const key = pbkdf2(sha256, 'password', 'salt', { dkLen: 32, c: Math.pow(2, 18) });
scrypt
Source: my-backend/node_modules/@noble/hashes/src/scrypt.ts
Signature: scrypt(password: KDFInput, salt: KDFInput, opts: ScryptOpts)
JSDoc:
RFC 7914 Scrypt KDF. Can be used to create a key from password and salt. @module / import { pbkdf2 } from './pbkdf2.ts'; import { sha256 } from './sha2.ts'; // prettier-ignore import { anumber, asyncLoop, checkOpts, clean, type KDFInput, rotl, swap32IfBE, u32 } from './utils.ts';
// The main Scrypt loop: uses Salsa extensively. // Six versions of the function were tried, this is the fastest one. // prettier-ignore function XorAndSalsa( prev: Uint32Array, pi: number, input: Uint32Array, ii: number, out: Uint32Array, oi: number ) { // Based on https://cr.yp.to/salsa20.html // Xor blocks let y00 = prev[pi++] ^ input[ii++], y01 = prev[pi++] ^ input[ii++]; let y02 = prev[pi++] ^ input[ii++], y03 = prev[pi++] ^ input[ii++]; let y04 = prev[pi++] ^ input[ii++], y05 = prev[pi++] ^ input[ii++]; let y06 = prev[pi++] ^ input[ii++], y07 = prev[pi++] ^ input[ii++]; let y08 = prev[pi++] ^ input[ii++], y09 = prev[pi++] ^ input[ii++]; let y10 = prev[pi++] ^ input[ii++], y11 = prev[pi++] ^ input[ii++]; let y12 = prev[pi++] ^ input[ii++], y13 = prev[pi++] ^ input[ii++]; let y14 = prev[pi++] ^ input[ii++], y15 = prev[pi++] ^ input[ii++]; // Save state to temporary variables (salsa) let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15; // Main loop (salsa) for (let i = 0; i < 8; i += 2) { x04 ^= rotl(x00 + x12 | 0, 7); x08 ^= rotl(x04 + x00 | 0, 9); x12 ^= rotl(x08 + x04 | 0, 13); x00 ^= rotl(x12 + x08 | 0, 18); x09 ^= rotl(x05 + x01 | 0, 7); x13 ^= rotl(x09 + x05 | 0, 9); x01 ^= rotl(x13 + x09 | 0, 13); x05 ^= rotl(x01 + x13 | 0, 18); x14 ^= rotl(x10 + x06 | 0, 7); x02 ^= rotl(x14 + x10 | 0, 9); x06 ^= rotl(x02 + x14 | 0, 13); x10 ^= rotl(x06 + x02 | 0, 18); x03 ^= rotl(x15 + x11 | 0, 7); x07 ^= rotl(x03 + x15 | 0, 9); x11 ^= rotl(x07 + x03 | 0, 13); x15 ^= rotl(x11 + x07 | 0, 18); x01 ^= rotl(x00 + x03 | 0, 7); x02 ^= rotl(x01 + x00 | 0, 9); x03 ^= rotl(x02 + x01 | 0, 13); x00 ^= rotl(x03 + x02 | 0, 18); x06 ^= rotl(x05 + x04 | 0, 7); x07 ^= rotl(x06 + x05 | 0, 9); x04 ^= rotl(x07 + x06 | 0, 13); x05 ^= rotl(x04 + x07 | 0, 18); x11 ^= rotl(x10 + x09 | 0, 7); x08 ^= rotl(x11 + x10 | 0, 9); x09 ^= rotl(x08 + x11 | 0, 13); x10 ^= rotl(x09 + x08 | 0, 18); x12 ^= rotl(x15 + x14 | 0, 7); x13 ^= rotl(x12 + x15 | 0, 9); x14 ^= rotl(x13 + x12 | 0, 13); x15 ^= rotl(x14 + x13 | 0, 18); } // Write output (salsa) out[oi++] = (y00 + x00) | 0; out[oi++] = (y01 + x01) | 0; out[oi++] = (y02 + x02) | 0; out[oi++] = (y03 + x03) | 0; out[oi++] = (y04 + x04) | 0; out[oi++] = (y05 + x05) | 0; out[oi++] = (y06 + x06) | 0; out[oi++] = (y07 + x07) | 0; out[oi++] = (y08 + x08) | 0; out[oi++] = (y09 + x09) | 0; out[oi++] = (y10 + x10) | 0; out[oi++] = (y11 + x11) | 0; out[oi++] = (y12 + x12) | 0; out[oi++] = (y13 + x13) | 0; out[oi++] = (y14 + x14) | 0; out[oi++] = (y15 + x15) | 0; }
function BlockMix(input: Uint32Array, ii: number, out: Uint32Array, oi: number, r: number) { // The block B is r 128-byte chunks (which is equivalent of 2r 64-byte chunks) let head = oi + 0; let tail = oi + 16 * r; for (let i = 0; i < 16; i++) out[tail + i] = input[ii + (2 * r - 1) * 16 + i]; // X ← B[2r−1] for (let i = 0; i < r; i++, head += 16, ii += 16) { // We write odd & even Yi at same time. Even: 0bXXXXX0 Odd: 0bXXXXX1 XorAndSalsa(out, tail, input, ii, out, head); // head[i] = Salsa(blockIn[2i] ^ tail[i-1]) if (i > 0) tail += 16; // First iteration overwrites tmp value in tail XorAndSalsa(out, head, input, (ii += 16), out, tail); // tail[i] = Salsa(blockIn[2i+1] ^ head[i]) } }
export type ScryptOpts = { N: number; // cost factor r: number; // block size p: number; // parallelization dkLen?: number; // key length asyncTick?: number; // block execution max time maxmem?: number; onProgress?: (progress: number) => void; };
// Common prologue and epilogue for sync/async functions function scryptInit(password: KDFInput, salt: KDFInput, _opts?: ScryptOpts) { // Maxmem - 1GB+1KB by default const opts = checkOpts( { dkLen: 32, asyncTick: 10, maxmem: 1024 ** 3 + 1024, }, _opts ); const { N, r, p, dkLen, asyncTick, maxmem, onProgress } = opts; anumber(N); anumber(r); anumber(p); anumber(dkLen); anumber(asyncTick); anumber(maxmem); if (onProgress !== undefined && typeof onProgress !== 'function') throw new Error('progressCb should be function'); const blockSize = 128 * r; const blockSize32 = blockSize / 4;
// Max N is 2^32 (Integrify is 32-bit). Real limit is 2^22: JS engines Uint8Array limit is 4GB in 2024.
// Spec check N >= 2^(blockSize / 8) is not done for compat with popular libs,
// which used incorrect r: 1, p: 8. Also, the check seems to be a spec error:
// https://www.rfc-editor.org/errata_search.php?rfc=7914
const pow32 = Math.pow(2, 32);
if (N <= 1 || (N & (N - 1)) !== 0 || N > pow32) {
throw new Error('Scrypt: N must be larger than 1, a power of 2, and less than 2^32');
}
if (p < 0 || p > ((pow32 - 1) * 32) / blockSize) {
throw new Error(
'Scrypt: p must be a positive integer less than or equal to ((2^32 - 1) * 32) / (128 * r)'
);
}
if (dkLen < 0 || dkLen > (pow32 - 1) * 32) {
throw new Error(
'Scrypt: dkLen should be positive integer less than or equal to (2^32 - 1) * 32'
);
}
const memUsed = blockSize * (N + p);
if (memUsed > maxmem) {
throw new Error(
'Scrypt: memused is bigger than maxMem. Expected 128 * r * (N + p) > maxmem of ' + maxmem
);
}
// [B0...Bp−1] ← PBKDF2HMAC-SHA256(Passphrase, Salt, 1, blockSize*ParallelizationFactor)
// Since it has only one iteration there is no reason to use async variant
const B = pbkdf2(sha256, password, salt, { c: 1, dkLen: blockSize * p });
const B32 = u32(B);
// Re-used between parallel iterations. Array(iterations) of B
const V = u32(new Uint8Array(blockSize * N));
const tmp = u32(new Uint8Array(blockSize));
let blockMixCb = () => {};
if (onProgress) {
const totalBlockMix = 2 * N * p;
// Invoke callback if progress changes from 10.01 to 10.02
// Allows to draw smooth progress bar on up to 8K screen
const callbackPer = Math.max(Math.floor(totalBlockMix / 10000), 1);
let blockMixCnt = 0;
blockMixCb = () => {
blockMixCnt++;
if (onProgress && (!(blockMixCnt % callbackPer) || blockMixCnt === totalBlockMix))
onProgress(blockMixCnt / totalBlockMix);
};
}
return { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick };
}
function scryptOutput( password: KDFInput, dkLen: number, B: Uint8Array, V: Uint32Array, tmp: Uint32Array ) { const res = pbkdf2(sha256, password, B, { c: 1, dkLen }); clean(B, V, tmp); return res; }
/
Scrypt KDF from RFC 7914.
@param password - pass
@param salt - salt
@param opts - parameters
- N is cpu/mem work factor (power of 2 e.g. 218)
- r is block size (8 is common), fine-tunes sequential memory read size and performance
- p is parallelization factor (1 is common)
- dkLen is output key length in bytes e.g. 32.
- asyncTick - (default: 10) max time in ms for which async function can block execution
- maxmem - (default: 1024 ** 3 + 1024 aka 1GB+1KB). A limit that the app could use for scrypt
- onProgress - callback function that would be executed for progress report
@returns Derived key
@example
scrypt('password', 'salt', { N: 2**18, r: 8, p: 1, dkLen: 32 });
keccakP
Source: my-backend/node_modules/@noble/hashes/src/sha3.ts
Signature: keccakP(s: Uint32Array, rounds: number = 24)
JSDoc:
SHA3 (keccak) hash function, based on a new "Sponge function" design. Different from older hashes, the internal state is bigger than output size.
Check out FIPS-202, Website, the differences between SHA-3 and Keccak.
Check out sha3-addons module for cSHAKE, k12, and others.
@module
/
import { rotlBH, rotlBL, rotlSH, rotlSL, split } from './_u64.ts';
// prettier-ignore
import {
abytes, aexists, anumber, aoutput,
clean, createHasher, createXOFer, Hash,
swap32IfBE,
toBytes, u32,
type CHash, type CHashXO, type HashXOF, type Input
} from './utils.ts';
// No PURE annotations in sha3 header: // EVERYTHING is in fact used on every export. // Various per round constants calculations const _0n = BigInt(0); const _1n = BigInt(1); const _2n = BigInt(2); const _7n = BigInt(7); const _256n = BigInt(256); const _0x71n = BigInt(0x71); const SHA3_PI: number[] = []; const SHA3_ROTL: number[] = []; const _SHA3_IOTA: bigint[] = []; for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) { // Pi [x, y] = [y, (2 * x + 3 * y) % 5]; SHA3_PI.push(2 * (5 * y + x)); // Rotational SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64); // Iota let t = _0n; for (let j = 0; j < 7; j++) { R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n; if (R & _2n) t ^= _1n << ((_1n << / @PURE / BigInt(j)) - _1n); } _SHA3_IOTA.push(t); } const IOTAS = split(_SHA3_IOTA, true); const SHA3_IOTA_H = IOTAS0; const SHA3_IOTA_L = IOTAS[1];
// Left rotation (without 0, 32, 64) const rotlH = (h: number, l: number, s: number) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s)); const rotlL = (h: number, l: number, s: number) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s));
/** keccakf1600 internal function, additionally allows to adjust round count.
isBytes
Source: my-backend/node_modules/@noble/hashes/src/utils.ts
Signature: isBytes(a: unknown)
JSDoc:
Utilities for hex, bytes, CSPRNG. @module / /! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) /
// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
// node.js versions earlier than v19 don't declare it in global scope.
// For node.js, package.json#exports field mapping rewrites import
// from crypto to cryptoNode, which imports native module.
// Makes the utils un-importable in browsers without a bundler.
// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.
import { crypto } from '@noble/hashes/crypto';
/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.
anumber
Source: my-backend/node_modules/@noble/hashes/src/utils.ts
Signature: anumber(n: number)
JSDoc:
Asserts something is positive integer.
abytes
Source: my-backend/node_modules/@noble/hashes/src/utils.ts
Signature: abytes(b: Uint8Array | undefined, ...lengths: number[])
JSDoc:
Asserts something is Uint8Array.
ahash
Source: my-backend/node_modules/@noble/hashes/src/utils.ts
Signature: ahash(h: IHash)
JSDoc:
Asserts something is hash
aexists
Source: my-backend/node_modules/@noble/hashes/src/utils.ts
Signature: aexists(instance: any, checkFinished = true)
JSDoc:
Asserts a hash instance has not been destroyed / finished
aoutput
Source: my-backend/node_modules/@noble/hashes/src/utils.ts
Signature: aoutput(out: any, instance: any)
JSDoc:
Asserts output is properly-sized byte array
u8
Source: my-backend/node_modules/@noble/hashes/src/utils.ts
Signature: u8(arr: TypedArray)
JSDoc:
Generic type encompassing 8/16/32-byte arrays - but not 64-byte. */ // prettier-ignore export type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array | Uint16Array | Int16Array | Uint32Array | Int32Array;
/** Cast u8 / u16 / u32 to u8.
u32
Source: my-backend/node_modules/@noble/hashes/src/utils.ts
Signature: u32(arr: TypedArray)
JSDoc:
Cast u8 / u16 / u32 to u32.
clean
Source: my-backend/node_modules/@noble/hashes/src/utils.ts
Signature: clean(...arrays: TypedArray[])
JSDoc:
Zeroize a byte array. Warning: JS provides no guarantees.
createView
Source: my-backend/node_modules/@noble/hashes/src/utils.ts
Signature: createView(arr: TypedArray)
JSDoc:
Create DataView of an array for easy byte-level manipulation.
rotr
Source: my-backend/node_modules/@noble/hashes/src/utils.ts
Signature: rotr(word: number, shift: number)
JSDoc:
The rotate right (circular right shift) operation for uint32
rotl
Source: my-backend/node_modules/@noble/hashes/src/utils.ts
Signature: rotl(word: number, shift: number)
JSDoc:
The rotate left (circular left shift) operation for uint32
byteSwap
Source: my-backend/node_modules/@noble/hashes/src/utils.ts
Signature: byteSwap(word: number)
JSDoc:
Is current platform little-endian? Most are. Big-Endian platform: IBM / export const isLE: boolean = / @PURE */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)0 === 0x44)();
/** The byte swap operation for uint32
byteSwap32
Source: my-backend/node_modules/@noble/hashes/src/utils.ts
Signature: byteSwap32(arr: Uint32Array)
JSDoc:
Conditionally byte swap if on a big-endian platform */ export const swap8IfBE: (n: number) => number = isLE ? (n: number) => n : (n: number) => byteSwap(n);
/ @deprecated */ export const byteSwapIfBE: typeof swap8IfBE = swap8IfBE; / In place byte swap for Uint32Array
bytesToHex
Source: my-backend/node_modules/@noble/hashes/src/utils.ts
Signature: bytesToHex(bytes: Uint8Array)
JSDoc:
Convert byte array to hex string. Uses built-in function, when available. @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
hexToBytes
Source: my-backend/node_modules/@noble/hashes/src/utils.ts
Signature: hexToBytes(hex: string)
JSDoc:
Convert hex string to byte array. Uses built-in function, when available. @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
utf8ToBytes
Source: my-backend/node_modules/@noble/hashes/src/utils.ts
Signature: utf8ToBytes(str: string)
JSDoc:
There is no setImmediate in browser and setTimeout is slow.
Call of async fn will return Promise, which will be fullfiled only on
next scheduler queue processing step and this is exactly what we need.
/
export const nextTick = async (): Promise
/* Returns control to thread each 'tick' ms to avoid blocking. /
export async function asyncLoop(
iters: number,
tick: number,
cb: (i: number) => void
): Promise
// Global symbols, but ts doesn't see them: https://github.com/microsoft/TypeScript/issues/31535 declare const TextEncoder: any; declare const TextDecoder: any;
/** Converts string to bytes using UTF8 encoding. @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])
bytesToUtf8
Source: my-backend/node_modules/@noble/hashes/src/utils.ts
Signature: bytesToUtf8(bytes: Uint8Array)
JSDoc:
Converts bytes to string using UTF8 encoding. @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'
toBytes
Source: my-backend/node_modules/@noble/hashes/src/utils.ts
Signature: toBytes(data: Input)
JSDoc:
Accepted input of hash functions. Strings are converted to byte arrays. / export type Input = string | Uint8Array; /* Normalizes (non-hex) string or Uint8Array to Uint8Array. Warning: when Uint8Array is passed, it would NOT get copied. Keep in mind for future mutable operations.
kdfInputToBytes
Source: my-backend/node_modules/@noble/hashes/src/utils.ts
Signature: kdfInputToBytes(data: KDFInput)
JSDoc:
KDFs can accept string or Uint8Array for user convenience. / export type KDFInput = string | Uint8Array; /* Helper for KDFs: consumes uint8array or string. When string is passed, does utf8 decoding, using TextDecoder.
concatBytes
Source: my-backend/node_modules/@noble/hashes/src/utils.ts
Signature: concatBytes(...arrays: Uint8Array[])
JSDoc:
Copies several Uint8Arrays into one.
createHasher
Source: my-backend/node_modules/@noble/hashes/src/utils.ts
Signature: createHasher(<T extends Hash<T>>(
hashCons: ()
JSDoc:
Hash interface. */ export type IHash = { (data: Uint8Array): Uint8Array; blockLen: number; outputLen: number; create: any; };
/ For runtime check if class implements interface */
export abstract class Hashdestroy() when zeroing is necessary.
/
abstract destroy(): void;
/**
Clones hash instance. Unsafe: doesn't check whether to is valid. Can be used as clone()
when no options are passed.
Reasons to use _cloneInto instead of clone: 1) performance 2) reuse instance => all internal
buffers are overwritten => causes buffer overwrite which is used for digest in some cases.
There are no guarantees for clean-up because it's impossible in JS.
/
abstract _cloneInto(to?: T): T;
// Safe version that clones internal state
abstract clone(): T;
}
/**
XOF: streaming API to read digest in chunks.
Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name.
When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot
destroy state, next call can require more bytes.
/
export type HashXOF
/ Hash function */
export type CHash = ReturnType
/** Wraps hash function, creating an interface on top of it
randomBytes
Source: my-backend/node_modules/@noble/hashes/src/utils.ts
Signature: randomBytes(bytesLength = 32)
JSDoc:
Cryptographically secure PRNG. Uses internal OS-level crypto.getRandomValues.
isLE
Source: my-backend/node_modules/@noble/hashes/utils.js
Signature: isLE(= (()
JSDoc:
Utilities for hex, bytes, CSPRNG.
@module
/
/! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) /
Object.defineProperty(exports, "__esModule", { value: true });
exports.wrapXOFConstructorWithOpts = exports.wrapConstructorWithOpts = exports.wrapConstructor = exports.Hash = exports.nextTick = exports.swap32IfBE = exports.byteSwapIfBE = exports.swap8IfBE = exports.isLE = void 0;
exports.isBytes = isBytes;
exports.anumber = anumber;
exports.abytes = abytes;
exports.ahash = ahash;
exports.aexists = aexists;
exports.aoutput = aoutput;
exports.u8 = u8;
exports.u32 = u32;
exports.clean = clean;
exports.createView = createView;
exports.rotr = rotr;
exports.rotl = rotl;
exports.byteSwap = byteSwap;
exports.byteSwap32 = byteSwap32;
exports.bytesToHex = bytesToHex;
exports.hexToBytes = hexToBytes;
exports.asyncLoop = asyncLoop;
exports.utf8ToBytes = utf8ToBytes;
exports.bytesToUtf8 = bytesToUtf8;
exports.toBytes = toBytes;
exports.kdfInputToBytes = kdfInputToBytes;
exports.concatBytes = concatBytes;
exports.checkOpts = checkOpts;
exports.createHasher = createHasher;
exports.createOptHasher = createOptHasher;
exports.createXOFer = createXOFer;
exports.randomBytes = randomBytes;
// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
// node.js versions earlier than v19 don't declare it in global scope.
// For node.js, package.json#exports field mapping rewrites import
// from crypto to cryptoNode, which imports native module.
// Makes the utils un-importable in browsers without a bundler.
// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.
const crypto_1 = require("@noble/hashes/crypto");
/ Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */
function isBytes(a) {
return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
}
/ Asserts something is positive integer. /
function anumber(n) {
if (!Number.isSafeInteger(n) || n < 0)
throw new Error('positive integer expected, got ' + n);
}
/ Asserts something is Uint8Array. /
function abytes(b, ...lengths) {
if (!isBytes(b))
throw new Error('Uint8Array expected');
if (lengths.length > 0 && !lengths.includes(b.length))
throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);
}
/ Asserts something is hash */
function ahash(h) {
if (typeof h !== 'function' || typeof h.create !== 'function')
throw new Error('Hash should be wrapped by utils.createHasher');
anumber(h.outputLen);
anumber(h.blockLen);
}
/ Asserts a hash instance has not been destroyed / finished /
function aexists(instance, checkFinished = true) {
if (instance.destroyed)
throw new Error('Hash instance has been destroyed');
if (checkFinished && instance.finished)
throw new Error('Hash#digest() has already been called');
}
/ Asserts output is properly-sized byte array /
function aoutput(out, instance) {
abytes(out);
const min = instance.outputLen;
if (out.length < min) {
throw new Error('digestInto() expects output buffer of length at least ' + min);
}
}
/ Cast u8 / u16 / u32 to u8. */
function u8(arr) {
return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
}
/ Cast u8 / u16 / u32 to u32. /
function u32(arr) {
return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
}
/ Zeroize a byte array. Warning: JS provides no guarantees. /
function clean(...arrays) {
for (let i = 0; i < arrays.length; i++) {
arrays[i].fill(0);
}
}
/ Create DataView of an array for easy byte-level manipulation. */
function createView(arr) {
return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
}
/ The rotate right (circular right shift) operation for uint32 /
function rotr(word, shift) {
return (word << (32 - shift)) | (word >>> shift);
}
/ The rotate left (circular left shift) operation for uint32 /
function rotl(word, shift) {
return (word << shift) | ((word >>> (32 - shift)) >>> 0);
}
/** Is current platform little-endian? Most are. Big-Endian platform: IBM
swap8IfBE
Source: my-backend/node_modules/@noble/hashes/utils.js
Signature: swap8IfBE(= exports.isLE
? (n)
JSDoc:
The byte swap operation for uint32 / function byteSwap(word) { return (((word << 24) & 0xff000000) | ((word << 8) & 0xff0000) | ((word >>> 8) & 0xff00) | ((word >>> 24) & 0xff)); } /* Conditionally byte swap if on a big-endian platform
byteSwapIfBE
Source: my-backend/node_modules/@noble/hashes/utils.js
Signature: byteSwapIfBE(= exports.swap8IfBE;
/** In place byte swap for Uint32Array */
function byteSwap32(arr)
JSDoc:
@deprecated
StandardType
Source: my-backend/node_modules/@sinclair/typebox/typebox.js
Signature: StandardType(= new StandardTypeBuilder()
JSDoc:
A registry for user defined types /
var TypeRegistry;
(function (TypeRegistry) {
const map = new Map();
/ Returns the entries in this registry /
function Entries() {
return new Map(map);
}
TypeRegistry.Entries = Entries;
/ Clears all user defined types */
function Clear() {
return map.clear();
}
TypeRegistry.Clear = Clear;
/ Returns true if this registry contains this kind /
function Has(kind) {
return map.has(kind);
}
TypeRegistry.Has = Has;
/ Sets a validation function for a user defined type /
function Set(kind, func) {
map.set(kind, func);
}
TypeRegistry.Set = Set;
/ Gets a custom validation function for a user defined type */
function Get(kind) {
return map.get(kind);
}
TypeRegistry.Get = Get;
})(TypeRegistry = exports.TypeRegistry || (exports.TypeRegistry = {}));
/ A registry for user defined string formats /
var FormatRegistry;
(function (FormatRegistry) {
const map = new Map();
/ Returns the entries in this registry /
function Entries() {
return new Map(map);
}
FormatRegistry.Entries = Entries;
/ Clears all user defined string formats */
function Clear() {
return map.clear();
}
FormatRegistry.Clear = Clear;
/ Returns true if the user defined string format exists /
function Has(format) {
return map.has(format);
}
FormatRegistry.Has = Has;
/ Sets a validation function for a user defined string format /
function Set(format, func) {
map.set(format, func);
}
FormatRegistry.Set = Set;
/ Gets a validation function for a user defined string format */
function Get(format) {
return map.get(format);
}
FormatRegistry.Get = Get;
})(FormatRegistry = exports.FormatRegistry || (exports.FormatRegistry = {}));
// --------------------------------------------------------------------------
// TypeGuard
// --------------------------------------------------------------------------
class TypeGuardUnknownTypeError extends Error {
constructor(schema) {
super('TypeGuard: Unknown type');
this.schema = schema;
}
}
exports.TypeGuardUnknownTypeError = TypeGuardUnknownTypeError;
/ Provides functions to test if JavaScript values are TypeBox types /
var TypeGuard;
(function (TypeGuard) {
function IsObject(value) {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
function IsArray(value) {
return typeof value === 'object' && value !== null && Array.isArray(value);
}
function IsPattern(value) {
try {
new RegExp(value);
return true;
}
catch {
return false;
}
}
function IsControlCharacterFree(value) {
if (typeof value !== 'string')
return false;
for (let i = 0; i < value.length; i++) {
const code = value.charCodeAt(i);
if ((code >= 7 && code <= 13) || code === 27 || code === 127) {
return false;
}
}
return true;
}
function IsBigInt(value) {
return typeof value === 'bigint';
}
function IsString(value) {
return typeof value === 'string';
}
function IsNumber(value) {
return typeof value === 'number' && globalThis.Number.isFinite(value);
}
function IsBoolean(value) {
return typeof value === 'boolean';
}
function IsOptionalBigInt(value) {
return value === undefined || (value !== undefined && IsBigInt(value));
}
function IsOptionalNumber(value) {
return value === undefined || (value !== undefined && IsNumber(value));
}
function IsOptionalBoolean(value) {
return value === undefined || (value !== undefined && IsBoolean(value));
}
function IsOptionalString(value) {
return value === undefined || (value !== undefined && IsString(value));
}
function IsOptionalPattern(value) {
return value === undefined || (value !== undefined && IsString(value) && IsControlCharacterFree(value) && IsPattern(value));
}
function IsOptionalFormat(value) {
return value === undefined || (value !== undefined && IsString(value) && IsControlCharacterFree(value));
}
function IsOptionalSchema(value) {
return value === undefined || TSchema(value);
}
/ Returns true if the given schema is TAny /
function TAny(schema) {
return TKind(schema) && schema[exports.Kind] === 'Any' && IsOptionalString(schema.$id);
}
TypeGuard.TAny = TAny;
/ Returns true if the given schema is TArray */
function TArray(schema) {
return (TKind(schema) &&
schema[exports.Kind] === 'Array' &&
schema.type === 'array' &&
IsOptionalString(schema.$id) &&
TSchema(schema.items) &&
IsOptionalNumber(schema.minItems) &&
IsOptionalNumber(schema.maxItems) &&
IsOptionalBoolean(schema.uniqueItems));
}
TypeGuard.TArray = TArray;
/ Returns true if the given schema is TBigInt /
function TBigInt(schema) {
// prettier-ignore
return (TKind(schema) &&
schema[exports.Kind] === 'BigInt' &&
schema.type === 'null' &&
schema.typeOf === 'BigInt' &&
IsOptionalString(schema.$id) &&
IsOptionalBigInt(schema.multipleOf) &&
IsOptionalBigInt(schema.minimum) &&
IsOptionalBigInt(schema.maximum) &&
IsOptionalBigInt(schema.exclusiveMinimum) &&
IsOptionalBigInt(schema.exclusiveMaximum));
}
TypeGuard.TBigInt = TBigInt;
/ Returns true if the given schema is TBoolean /
function TBoolean(schema) {
// prettier-ignore
return (TKind(schema) &&
schema[exports.Kind] === 'Boolean' &&
schema.type === 'boolean' &&
IsOptionalString(schema.$id));
}
TypeGuard.TBoolean = TBoolean;
/ Returns true if the given schema is TConstructor */
function TConstructor(schema) {
// prettier-ignore
if (!(TKind(schema) &&
schema[exports.Kind] === 'Constructor' &&
schema.type === 'object' &&
schema.instanceOf === 'Constructor' &&
IsOptionalString(schema.$id) &&
IsArray(schema.parameters) &&
TSchema(schema.returns))) {
return false;
}
for (const parameter of schema.parameters) {
if (!TSchema(parameter))
return false;
}
return true;
}
TypeGuard.TConstructor = TConstructor;
/ Returns true if the given schema is TDate /
function TDate(schema) {
return (TKind(schema) &&
schema[exports.Kind] === 'Date' &&
schema.type === 'object' &&
schema.instanceOf === 'Date' &&
IsOptionalString(schema.$id) &&
IsOptionalNumber(schema.minimumTimestamp) &&
IsOptionalNumber(schema.maximumTimestamp) &&
IsOptionalNumber(schema.exclusiveMinimumTimestamp) &&
IsOptionalNumber(schema.exclusiveMaximumTimestamp));
}
TypeGuard.TDate = TDate;
/ Returns true if the given schema is TFunction /
function TFunction(schema) {
// prettier-ignore
if (!(TKind(schema) &&
schema[exports.Kind] === 'Function' &&
schema.type === 'object' &&
schema.instanceOf === 'Function' &&
IsOptionalString(schema.$id) &&
IsArray(schema.parameters) &&
TSchema(schema.returns))) {
return false;
}
for (const parameter of schema.parameters) {
if (!TSchema(parameter))
return false;
}
return true;
}
TypeGuard.TFunction = TFunction;
/ Returns true if the given schema is TInteger */
function TInteger(schema) {
return (TKind(schema) &&
schema[exports.Kind] === 'Integer' &&
schema.type === 'integer' &&
IsOptionalString(schema.$id) &&
IsOptionalNumber(schema.multipleOf) &&
IsOptionalNumber(schema.minimum) &&
IsOptionalNumber(schema.maximum) &&
IsOptionalNumber(schema.exclusiveMinimum) &&
IsOptionalNumber(schema.exclusiveMaximum));
}
TypeGuard.TInteger = TInteger;
/ Returns true if the given schema is TIntersect /
function TIntersect(schema) {
// prettier-ignore
if (!(TKind(schema) &&
schema[exports.Kind] === 'Intersect' &&
IsArray(schema.allOf) &&
IsOptionalString(schema.type) &&
(IsOptionalBoolean(schema.unevaluatedProperties) || IsOptionalSchema(schema.unevaluatedProperties)) &&
IsOptionalString(schema.$id))) {
return false;
}
if ('type' in schema && schema.type !== 'object') {
return false;
}
for (const inner of schema.allOf) {
if (!TSchema(inner))
return false;
}
return true;
}
TypeGuard.TIntersect = TIntersect;
/ Returns true if the given schema is TKind /
function TKind(schema) {
return IsObject(schema) && exports.Kind in schema && typeof schema[exports.Kind] === 'string'; // TS 4.1.5: any required for symbol indexer
}
TypeGuard.TKind = TKind;
/ Returns true if the given schema is TLiteral */
function TLiteral(schema) {
// prettier-ignore
return (TKind(schema) &&
schema[exports.Kind] === 'Literal' &&
IsOptionalString(schema.$id) &&
(IsString(schema.const) ||
IsNumber(schema.const) ||
IsBoolean(schema.const) ||
IsBigInt(schema.const)));
}
TypeGuard.TLiteral = TLiteral;
/ Returns true if the given schema is TNever /
function TNever(schema) {
return TKind(schema) && schema[exports.Kind] === 'Never' && IsObject(schema.not) && globalThis.Object.getOwnPropertyNames(schema.not).length === 0;
}
TypeGuard.TNever = TNever;
/ Returns true if the given schema is TNot /
function TNot(schema) {
// prettier-ignore
return (TKind(schema) &&
schema[exports.Kind] === 'Not' &&
IsArray(schema.allOf) &&
schema.allOf.length === 2 &&
IsObject(schema.allOf0) &&
TSchema(schema.allOf0.not) &&
TSchema(schema.allOf[1]));
}
TypeGuard.TNot = TNot;
/ Returns true if the given schema is TNull */
function TNull(schema) {
// prettier-ignore
return (TKind(schema) &&
schema[exports.Kind] === 'Null' &&
schema.type === 'null' &&
IsOptionalString(schema.$id));
}
TypeGuard.TNull = TNull;
/ Returns true if the given schema is TNumber /
function TNumber(schema) {
return (TKind(schema) &&
schema[exports.Kind] === 'Number' &&
schema.type === 'number' &&
IsOptionalString(schema.$id) &&
IsOptionalNumber(schema.multipleOf) &&
IsOptionalNumber(schema.minimum) &&
IsOptionalNumber(schema.maximum) &&
IsOptionalNumber(schema.exclusiveMinimum) &&
IsOptionalNumber(schema.exclusiveMaximum));
}
TypeGuard.TNumber = TNumber;
/ Returns true if the given schema is TObject /
function TObject(schema) {
if (!(TKind(schema) &&
schema[exports.Kind] === 'Object' &&
schema.type === 'object' &&
IsOptionalString(schema.$id) &&
IsObject(schema.properties) &&
(IsOptionalBoolean(schema.additionalProperties) || IsOptionalSchema(schema.additionalProperties)) &&
IsOptionalNumber(schema.minProperties) &&
IsOptionalNumber(schema.maxProperties))) {
return false;
}
for (const [key, value] of Object.entries(schema.properties)) {
if (!IsControlCharacterFree(key))
return false;
if (!TSchema(value))
return false;
}
return true;
}
TypeGuard.TObject = TObject;
/ Returns true if the given schema is TPromise */
function TPromise(schema) {
// prettier-ignore
return (TKind(schema) &&
schema[exports.Kind] === 'Promise' &&
schema.type === 'object' &&
schema.instanceOf === 'Promise' &&
IsOptionalString(schema.$id) &&
TSchema(schema.item));
}
TypeGuard.TPromise = TPromise;
/ Returns true if the given schema is TRecord /
function TRecord(schema) {
// prettier-ignore
if (!(TKind(schema) &&
schema[exports.Kind] === 'Record' &&
schema.type === 'object' &&
IsOptionalString(schema.$id) &&
schema.additionalProperties === false &&
IsObject(schema.patternProperties))) {
return false;
}
const keys = Object.keys(schema.patternProperties);
if (keys.length !== 1) {
return false;
}
if (!IsPattern(keys0)) {
return false;
}
if (!TSchema(schema.patternProperties[keys[0]])) {
return false;
}
return true;
}
TypeGuard.TRecord = TRecord;
/ Returns true if the given schema is TRef /
function TRef(schema) {
// prettier-ignore
return (TKind(schema) &&
schema[exports.Kind] === 'Ref' &&
IsOptionalString(schema.$id) &&
IsString(schema.$ref));
}
TypeGuard.TRef = TRef;
/ Returns true if the given schema is TString */
function TString(schema) {
return (TKind(schema) &&
schema[exports.Kind] === 'String' &&
schema.type === 'string' &&
IsOptionalString(schema.$id) &&
IsOptionalNumber(schema.minLength) &&
IsOptionalNumber(schema.maxLength) &&
IsOptionalPattern(schema.pattern) &&
IsOptionalFormat(schema.format));
}
TypeGuard.TString = TString;
/ Returns true if the given schema is TSymbol /
function TSymbol(schema) {
// prettier-ignore
return (TKind(schema) &&
schema[exports.Kind] === 'Symbol' &&
schema.type === 'null' &&
schema.typeOf === 'Symbol' &&
IsOptionalString(schema.$id));
}
TypeGuard.TSymbol = TSymbol;
/ Returns true if the given schema is TTemplateLiteral /
function TTemplateLiteral(schema) {
// prettier-ignore
return (TKind(schema) &&
schema[exports.Kind] === 'TemplateLiteral' &&
schema.type === 'string' &&
IsString(schema.pattern) &&
schema.pattern0 === '^' &&
schema.pattern[schema.pattern.length - 1] === '$');
}
TypeGuard.TTemplateLiteral = TTemplateLiteral;
/ Returns true if the given schema is TThis */
function TThis(schema) {
// prettier-ignore
return (TKind(schema) &&
schema[exports.Kind] === 'This' &&
IsOptionalString(schema.$id) &&
IsString(schema.$ref));
}
TypeGuard.TThis = TThis;
/ Returns true if the given schema is TTuple /
function TTuple(schema) {
// prettier-ignore
if (!(TKind(schema) &&
schema[exports.Kind] === 'Tuple' &&
schema.type === 'array' &&
IsOptionalString(schema.$id) &&
IsNumber(schema.minItems) &&
IsNumber(schema.maxItems) &&
schema.minItems === schema.maxItems)) {
return false;
}
if (schema.items === undefined && schema.additionalItems === undefined && schema.minItems === 0) {
return true;
}
if (!IsArray(schema.items)) {
return false;
}
for (const inner of schema.items) {
if (!TSchema(inner))
return false;
}
return true;
}
TypeGuard.TTuple = TTuple;
/ Returns true if the given schema is TUndefined /
function TUndefined(schema) {
// prettier-ignore
return (TKind(schema) &&
schema[exports.Kind] === 'Undefined' &&
schema.type === 'null' &&
schema.typeOf === 'Undefined' &&
IsOptionalString(schema.$id));
}
TypeGuard.TUndefined = TUndefined;
/ Returns true if the given schema is TUnion */
function TUnion(schema) {
// prettier-ignore
if (!(TKind(schema) &&
schema[exports.Kind] === 'Union' &&
IsArray(schema.anyOf) &&
IsOptionalString(schema.$id))) {
return false;
}
for (const inner of schema.anyOf) {
if (!TSchema(inner))
return false;
}
return true;
}
TypeGuard.TUnion = TUnion;
/ Returns true if the given schema is TUnionRecord. This is used to invert the extends logic.
return right[exports.Hint] === 'Record' ? TypeExtendsResult.True : TypeExtendsResult.False;
}
if (TypeGuard.TRecord(left) && TypeGuard.TNumber(RecordKey(left))) {
return IsObjectPropertyCount(right, 0) ? TypeExtendsResult.True : TypeExtendsResult.False;
}
return TypeExtendsResult.False;
}
function Object(left, right) {
if (TypeGuard.TIntersect(right))
return IntersectRight(left, right);
if (TypeGuard.TUnion(right))
return UnionRight(left, right);
if (TypeGuard.TUnknown(right))
return UnknownRight(left, right);
if (TypeGuard.TAny(right))
return AnyRight(left, right);
if (TypeGuard.TRecord(right))
return RecordRight(left, right);
if (!TypeGuard.TObject(right))
return TypeExtendsResult.False;
for (const key of globalThis.Object.keys(right.properties)) {
if (!(key in left.properties))
return TypeExtendsResult.False;
if (Property(left.properties[key], right.properties[key]) === TypeExtendsResult.False) {
return TypeExtendsResult.False;
}
}
return TypeExtendsResult.True;
}
// --------------------------------------------------------------------------
// Promise
// --------------------------------------------------------------------------
function Promise(left, right) {
if (TypeGuard.TIntersect(right))
return IntersectRight(left, right);
if (TypeGuard.TUnion(right))
return UnionRight(left, right);
if (TypeGuard.TUnknown(right))
return UnknownRight(left, right);
if (TypeGuard.TAny(right))
return AnyRight(left, right);
if (TypeGuard.TObject(right) && IsObjectPromiseLike(right))
return TypeExtendsResult.True;
if (!TypeGuard.TPromise(right))
return TypeExtendsResult.False;
return IntoBooleanResult(Visit(left.item, right.item));
}
// --------------------------------------------------------------------------
// Record
// --------------------------------------------------------------------------
function RecordKey(schema) {
if (exports.PatternNumberExact in schema.patternProperties)
return exports.Type.Number();
if (exports.PatternStringExact in schema.patternProperties)
return exports.Type.String();
throw Error('TypeExtends: Cannot get record key');
}
function RecordValue(schema) {
if (exports.PatternNumberExact in schema.patternProperties)
return schema.patternProperties[exports.PatternNumberExact];
if (exports.PatternStringExact in schema.patternProperties)
return schema.patternProperties[exports.PatternStringExact];
throw Error('TypeExtends: Cannot get record value');
}
function RecordRight(left, right) {
const Key = RecordKey(right);
const Value = RecordValue(right);
if (TypeGuard.TLiteral(left) && IsLiteralString(left) && TypeGuard.TNumber(Key) && IntoBooleanResult(Visit(left, Value)) === TypeExtendsResult.True)
return TypeExtendsResult.True;
if (TypeGuard.TUint8Array(left) && TypeGuard.TNumber(Key))
return Visit(left, Value);
if (TypeGuard.TString(left) && TypeGuard.TNumber(Key))
return Visit(left, Value);
if (TypeGuard.TArray(left) && TypeGuard.TNumber(Key))
return Visit(left, Value);
if (TypeGuard.TObject(left)) {
for (const key of globalThis.Object.keys(left.properties)) {
if (Property(Value, left.properties[key]) === TypeExtendsResult.False) {
return TypeExtendsResult.False;
}
}
return TypeExtendsResult.True;
}
return TypeExtendsResult.False;
}
function Record(left, right) {
const Value = RecordValue(left);
if (TypeGuard.TIntersect(right))
return IntersectRight(left, right);
if (TypeGuard.TUnion(right))
return UnionRight(left, right);
if (TypeGuard.TUnknown(right))
return UnknownRight(left, right);
if (TypeGuard.TAny(right))
return AnyRight(left, right);
if (TypeGuard.TObject(right))
return ObjectRight(left, right);
if (!TypeGuard.TRecord(right))
return TypeExtendsResult.False;
return Visit(Value, RecordValue(right));
}
// --------------------------------------------------------------------------
// String
// --------------------------------------------------------------------------
function StringRight(left, right) {
if (TypeGuard.TLiteral(left) && typeof left.const === 'string')
return TypeExtendsResult.True;
return TypeGuard.TString(left) ? TypeExtendsResult.True : TypeExtendsResult.False;
}
function String(left, right) {
if (TypeGuard.TIntersect(right))
return IntersectRight(left, right);
if (TypeGuard.TUnion(right))
return UnionRight(left, right);
if (TypeGuard.TNever(right))
return NeverRight(left, right);
if (TypeGuard.TUnknown(right))
return UnknownRight(left, right);
if (TypeGuard.TAny(right))
return AnyRight(left, right);
if (TypeGuard.TObject(right))
return ObjectRight(left, right);
if (TypeGuard.TRecord(right))
return RecordRight(left, right);
return TypeGuard.TString(right) ? TypeExtendsResult.True : TypeExtendsResult.False;
}
// --------------------------------------------------------------------------
// Symbol
// --------------------------------------------------------------------------
function Symbol(left, right) {
if (TypeGuard.TIntersect(right))
return IntersectRight(left, right);
if (TypeGuard.TUnion(right))
return UnionRight(left, right);
if (TypeGuard.TNever(right))
return NeverRight(left, right);
if (TypeGuard.TUnknown(right))
return UnknownRight(left, right);
if (TypeGuard.TAny(right))
return AnyRight(left, right);
if (TypeGuard.TObject(right))
return ObjectRight(left, right);
if (TypeGuard.TRecord(right))
return RecordRight(left, right);
return TypeGuard.TSymbol(right) ? TypeExtendsResult.True : TypeExtendsResult.False;
}
// --------------------------------------------------------------------------
// Tuple
// --------------------------------------------------------------------------
function TupleRight(left, right) {
if (TypeGuard.TUnknown(left))
return TypeExtendsResult.False;
if (TypeGuard.TAny(left))
return TypeExtendsResult.Union;
if (TypeGuard.TNever(left))
return TypeExtendsResult.True;
return TypeExtendsResult.False;
}
function IsArrayOfTuple(left, right) {
return TypeGuard.TArray(right) && left.items !== undefined && left.items.every((schema) => Visit(schema, right.items) === TypeExtendsResult.True);
}
function Tuple(left, right) {
if (TypeGuard.TIntersect(right))
return IntersectRight(left, right);
if (TypeGuard.TUnion(right))
return UnionRight(left, right);
if (TypeGuard.TUnknown(right))
return UnknownRight(left, right);
if (TypeGuard.TAny(right))
return AnyRight(left, right);
if (TypeGuard.TObject(right) && IsObjectArrayLike(right))
return TypeExtendsResult.True;
if (TypeGuard.TArray(right) && IsArrayOfTuple(left, right))
return TypeExtendsResult.True;
if (!TypeGuard.TTuple(right))
return TypeExtendsResult.False;
if ((left.items === undefined && right.items !== undefined) || (left.items !== undefined && right.items === undefined))
return TypeExtendsResult.False;
if (left.items === undefined && right.items === undefined)
return TypeExtendsResult.True;
return left.items.every((schema, index) => Visit(schema, right.items[index]) === TypeExtendsResult.True) ? TypeExtendsResult.True : TypeExtendsResult.False;
}
// --------------------------------------------------------------------------
// Uint8Array
// --------------------------------------------------------------------------
function Uint8Array(left, right) {
if (TypeGuard.TIntersect(right))
return IntersectRight(left, right);
if (TypeGuard.TUnion(right))
return UnionRight(left, right);
if (TypeGuard.TUnknown(right))
return UnknownRight(left, right);
if (TypeGuard.TAny(right))
return AnyRight(left, right);
if (TypeGuard.TObject(right))
return ObjectRight(left, right);
if (TypeGuard.TRecord(right))
return RecordRight(left, right);
return TypeGuard.TUint8Array(right) ? TypeExtendsResult.True : TypeExtendsResult.False;
}
// --------------------------------------------------------------------------
// Undefined
// --------------------------------------------------------------------------
function Undefined(left, right) {
if (TypeGuard.TIntersect(right))
return IntersectRight(left, right);
if (TypeGuard.TUnion(right))
return UnionRight(left, right);
if (TypeGuard.TNever(right))
return NeverRight(left, right);
if (TypeGuard.TUnknown(right))
return UnknownRight(left, right);
if (TypeGuard.TAny(right))
return AnyRight(left, right);
if (TypeGuard.TObject(right))
return ObjectRight(left, right);
if (TypeGuard.TRecord(right))
return RecordRight(left, right);
if (TypeGuard.TVoid(right))
return VoidRight(left, right);
return TypeGuard.TUndefined(right) ? TypeExtendsResult.True : TypeExtendsResult.False;
}
// --------------------------------------------------------------------------
// Union
// --------------------------------------------------------------------------
function UnionRight(left, right) {
return right.anyOf.some((schema) => Visit(left, schema) === TypeExtendsResult.True) ? TypeExtendsResult.True : TypeExtendsResult.False;
}
function Union(left, right) {
return left.anyOf.every((schema) => Visit(schema, right) === TypeExtendsResult.True) ? TypeExtendsResult.True : TypeExtendsResult.False;
}
// --------------------------------------------------------------------------
// Unknown
// --------------------------------------------------------------------------
function UnknownRight(left, right) {
return TypeExtendsResult.True;
}
function Unknown(left, right) {
if (TypeGuard.TIntersect(right))
return IntersectRight(left, right);
if (TypeGuard.TUnion(right))
return UnionRight(left, right);
if (TypeGuard.TAny(right))
return AnyRight(left, right);
if (TypeGuard.TString(right))
return StringRight(left, right);
if (TypeGuard.TNumber(right))
return NumberRight(left, right);
if (TypeGuard.TInteger(right))
return IntegerRight(left, right);
if (TypeGuard.TBoolean(right))
return BooleanRight(left, right);
if (TypeGuard.TArray(right))
return ArrayRight(left, right);
if (TypeGuard.TTuple(right))
return TupleRight(left, right);
if (TypeGuard.TObject(right))
return ObjectRight(left, right);
return TypeGuard.TUnknown(right) ? TypeExtendsResult.True : TypeExtendsResult.False;
}
// --------------------------------------------------------------------------
// Void
// --------------------------------------------------------------------------
function VoidRight(left, right) {
if (TypeGuard.TUndefined(left))
return TypeExtendsResult.True;
return TypeGuard.TUndefined(left) ? TypeExtendsResult.True : TypeExtendsResult.False;
}
function Void(left, right) {
if (TypeGuard.TIntersect(right))
return IntersectRight(left, right);
if (TypeGuard.TUnion(right))
return UnionRight(left, right);
if (TypeGuard.TUnknown(right))
return UnknownRight(left, right);
if (TypeGuard.TAny(right))
return AnyRight(left, right);
if (TypeGuard.TObject(right))
return ObjectRight(left, right);
return TypeGuard.TVoid(right) ? TypeExtendsResult.True : TypeExtendsResult.False;
}
function Visit(left, right) {
// template union remap
if (TypeGuard.TTemplateLiteral(left))
return Visit(TemplateLiteralResolver.Resolve(left), right);
if (TypeGuard.TTemplateLiteral(right))
return Visit(left, TemplateLiteralResolver.Resolve(right));
// standard extends
if (TypeGuard.TAny(left))
return Any(left, right);
if (TypeGuard.TArray(left))
return Array(left, right);
if (TypeGuard.TBigInt(left))
return BigInt(left, right);
if (TypeGuard.TBoolean(left))
return Boolean(left, right);
if (TypeGuard.TConstructor(left))
return Constructor(left, right);
if (TypeGuard.TDate(left))
return Date(left, right);
if (TypeGuard.TFunction(left))
return Function(left, right);
if (TypeGuard.TInteger(left))
return Integer(left, right);
if (TypeGuard.TIntersect(left))
return Intersect(left, right);
if (TypeGuard.TLiteral(left))
return Literal(left, right);
if (TypeGuard.TNever(left))
return Never(left, right);
if (TypeGuard.TNull(left))
return Null(left, right);
if (TypeGuard.TNumber(left))
return Number(left, right);
if (TypeGuard.TObject(left))
return Object(left, right);
if (TypeGuard.TRecord(left))
return Record(left, right);
if (TypeGuard.TString(left))
return String(left, right);
if (TypeGuard.TSymbol(left))
return Symbol(left, right);
if (TypeGuard.TTuple(left))
return Tuple(left, right);
if (TypeGuard.TPromise(left))
return Promise(left, right);
if (TypeGuard.TUint8Array(left))
return Uint8Array(left, right);
if (TypeGuard.TUndefined(left))
return Undefined(left, right);
if (TypeGuard.TUnion(left))
return Union(left, right);
if (TypeGuard.TUnknown(left))
return Unknown(left, right);
if (TypeGuard.TVoid(left))
return Void(left, right);
throw Error(TypeExtends: Unknown left type operand '${left[exports.Kind]}');
}
function Extends(left, right) {
return Visit(left, right);
}
TypeExtends.Extends = Extends;
})(TypeExtends = exports.TypeExtends || (exports.TypeExtends = {}));
// --------------------------------------------------------------------------
// TypeClone
// --------------------------------------------------------------------------
/ Specialized Clone for Types /
var TypeClone;
(function (TypeClone) {
function IsObject(value) {
return typeof value === 'object' && value !== null;
}
function IsArray(value) {
return globalThis.Array.isArray(value);
}
function Array(value) {
return value.map((value) => Visit(value));
}
function Object(value) {
const clonedProperties = globalThis.Object.getOwnPropertyNames(value).reduce((acc, key) => {
return { ...acc, [key]: Visit(value[key]) };
}, {});
const clonedSymbols = globalThis.Object.getOwnPropertySymbols(value).reduce((acc, key) => {
return { ...acc, [key]: Visit(value[key]) };
}, {});
return { ...clonedProperties, ...clonedSymbols };
}
function Visit(value) {
if (IsArray(value))
return Array(value);
if (IsObject(value))
return Object(value);
return value;
}
/ Clones a type. /
function Clone(schema, options) {
return { ...Visit(schema), ...options };
}
TypeClone.Clone = Clone;
})(TypeClone = exports.TypeClone || (exports.TypeClone = {}));
// --------------------------------------------------------------------------
// ObjectMap
// --------------------------------------------------------------------------
var ObjectMap;
(function (ObjectMap) {
function Intersect(schema, callback) {
// prettier-ignore
return exports.Type.Intersect(schema.allOf.map((inner) => Visit(inner, callback)), { ...schema });
}
function Union(schema, callback) {
// prettier-ignore
return exports.Type.Union(schema.anyOf.map((inner) => Visit(inner, callback)), { ...schema });
}
function Object(schema, callback) {
return callback(schema);
}
function Visit(schema, callback) {
// There are cases where users need to map objects with unregistered kinds. Using a TypeGuard here would
// prevent sub schema mapping as unregistered kinds will not pass TSchema checks. This is notable in the
// case of TObject where unregistered property kinds cause the TObject check to fail. As mapping is only
// used for composition, we use explicit checks instead.
if (schema[exports.Kind] === 'Intersect')
return Intersect(schema, callback);
if (schema[exports.Kind] === 'Union')
return Union(schema, callback);
if (schema[exports.Kind] === 'Object')
return Object(schema, callback);
return schema;
}
function Map(schema, callback, options) {
return { ...Visit(TypeClone.Clone(schema, {}), callback), ...options };
}
ObjectMap.Map = Map;
})(ObjectMap = exports.ObjectMap || (exports.ObjectMap = {}));
// --------------------------------------------------------------------------
// KeyResolver
// --------------------------------------------------------------------------
var KeyResolver;
(function (KeyResolver) {
function IsKeyable(schema) {
return TypeGuard.TIntersect(schema) || TypeGuard.TUnion(schema) || (TypeGuard.TObject(schema) && globalThis.Object.getOwnPropertyNames(schema.properties).length > 0);
}
function Intersect(schema) {
return [...schema.allOf.filter((schema) => IsKeyable(schema)).reduce((set, schema) => Visit(schema).map((key) => set.add(key))[0], new Set())];
}
function Union(schema) {
const sets = schema.anyOf.filter((schema) => IsKeyable(schema)).map((inner) => Visit(inner));
return [...sets.reduce((set, outer) => outer.map((key) => (sets.every((inner) => inner.includes(key)) ? set.add(key) : set))[0], new Set())];
}
function Object(schema) {
return globalThis.Object.keys(schema.properties);
}
function Visit(schema) {
if (TypeGuard.TIntersect(schema))
return Intersect(schema);
if (TypeGuard.TUnion(schema))
return Union(schema);
if (TypeGuard.TObject(schema))
return Object(schema);
return [];
}
function Resolve(schema) {
return Visit(schema);
}
KeyResolver.Resolve = Resolve;
})(KeyResolver = exports.KeyResolver || (exports.KeyResolver = {}));
// --------------------------------------------------------------------------
// TemplateLiteralPattern
// --------------------------------------------------------------------------
var TemplateLiteralPattern;
(function (TemplateLiteralPattern) {
function Escape(value) {
return value.replace(/[.+?^${}()|[]\]/g, '\$&');
}
function Visit(schema, acc) {
if (TypeGuard.TTemplateLiteral(schema)) {
const pattern = schema.pattern.slice(1, schema.pattern.length - 1);
return pattern;
}
else if (TypeGuard.TUnion(schema)) {
const tokens = schema.anyOf.map((schema) => Visit(schema, acc)).join('|');
return (${tokens});
}
else if (TypeGuard.TNumber(schema)) {
return ${acc}${exports.PatternNumber};
}
else if (TypeGuard.TInteger(schema)) {
return ${acc}${exports.PatternNumber};
}
else if (TypeGuard.TBigInt(schema)) {
return ${acc}${exports.PatternNumber};
}
else if (TypeGuard.TString(schema)) {
return ${acc}${exports.PatternString};
}
else if (TypeGuard.TLiteral(schema)) {
return ${acc}${Escape(schema.const.toString())};
}
else if (TypeGuard.TBoolean(schema)) {
return ${acc}${exports.PatternBoolean};
}
else if (TypeGuard.TNever(schema)) {
throw Error('TemplateLiteralPattern: TemplateLiteral cannot operate on types of TNever');
}
else {
throw Error(TemplateLiteralPattern: Unexpected Kind '${schema[exports.Kind]}');
}
}
function Create(kinds) {
return ^${kinds.map((schema) => Visit(schema, '')).join('')}\$;
}
TemplateLiteralPattern.Create = Create;
})(TemplateLiteralPattern = exports.TemplateLiteralPattern || (exports.TemplateLiteralPattern = {}));
// --------------------------------------------------------------------------------------
// TemplateLiteralResolver
// --------------------------------------------------------------------------------------
var TemplateLiteralResolver;
(function (TemplateLiteralResolver) {
function Resolve(template) {
const expression = TemplateLiteralParser.ParseExact(template.pattern);
if (!TemplateLiteralFinite.Check(expression))
return exports.Type.String();
const literals = [...TemplateLiteralGenerator.Generate(expression)].map((value) => exports.Type.Literal(value));
return exports.Type.Union(literals);
}
TemplateLiteralResolver.Resolve = Resolve;
})(TemplateLiteralResolver = exports.TemplateLiteralResolver || (exports.TemplateLiteralResolver = {}));
// --------------------------------------------------------------------------------------
// TemplateLiteralParser
// --------------------------------------------------------------------------------------
class TemplateLiteralParserError extends Error {
constructor(message) {
super(message);
}
}
exports.TemplateLiteralParserError = TemplateLiteralParserError;
var TemplateLiteralParser;
(function (TemplateLiteralParser) {
function IsNonEscaped(pattern, index, char) {
return pattern[index] === char && pattern.charCodeAt(index - 1) !== 92;
}
function IsOpenParen(pattern, index) {
return IsNonEscaped(pattern, index, '(');
}
function IsCloseParen(pattern, index) {
return IsNonEscaped(pattern, index, ')');
}
function IsSeparator(pattern, index) {
return IsNonEscaped(pattern, index, '|');
}
function IsGroup(pattern) {
if (!(IsOpenParen(pattern, 0) && IsCloseParen(pattern, pattern.length - 1)))
return false;
let count = 0;
for (let index = 0; index < pattern.length; index++) {
if (IsOpenParen(pattern, index))
count += 1;
if (IsCloseParen(pattern, index))
count -= 1;
if (count === 0 && index !== pattern.length - 1)
return false;
}
return true;
}
function InGroup(pattern) {
return pattern.slice(1, pattern.length - 1);
}
function IsPrecedenceOr(pattern) {
let count = 0;
for (let index = 0; index < pattern.length; index++) {
if (IsOpenParen(pattern, index))
count += 1;
if (IsCloseParen(pattern, index))
count -= 1;
if (IsSeparator(pattern, index) && count === 0)
return true;
}
return false;
}
function IsPrecedenceAnd(pattern) {
for (let index = 0; index < pattern.length; index++) {
if (IsOpenParen(pattern, index))
return true;
}
return false;
}
function Or(pattern) {
let [count, start] = [0, 0];
const expressions = [];
for (let index = 0; index < pattern.length; index++) {
if (IsOpenParen(pattern, index))
count += 1;
if (IsCloseParen(pattern, index))
count -= 1;
if (IsSeparator(pattern, index) && count === 0) {
const range = pattern.slice(start, index);
if (range.length > 0)
expressions.push(Parse(range));
start = index + 1;
}
}
const range = pattern.slice(start);
if (range.length > 0)
expressions.push(Parse(range));
if (expressions.length === 0)
return { type: 'const', const: '' };
if (expressions.length === 1)
return expressions0;
return { type: 'or', expr: expressions };
}
function And(pattern) {
function Group(value, index) {
if (!IsOpenParen(value, index))
throw new TemplateLiteralParserError(TemplateLiteralParser: Index must point to open parens);
let count = 0;
for (let scan = index; scan < value.length; scan++) {
if (IsOpenParen(value, scan))
count += 1;
if (IsCloseParen(value, scan))
count -= 1;
if (count === 0)
return [index, scan];
}
throw new TemplateLiteralParserError(TemplateLiteralParser: Unclosed group parens in expression);
}
function Range(pattern, index) {
for (let scan = index; scan < pattern.length; scan++) {
if (IsOpenParen(pattern, scan))
return [index, scan];
}
return [index, pattern.length];
}
const expressions = [];
for (let index = 0; index < pattern.length; index++) {
if (IsOpenParen(pattern, index)) {
const [start, end] = Group(pattern, index);
const range = pattern.slice(start, end + 1);
expressions.push(Parse(range));
index = end;
}
else {
const [start, end] = Range(pattern, index);
const range = pattern.slice(start, end);
if (range.length > 0)
expressions.push(Parse(range));
index = end - 1;
}
}
if (expressions.length === 0)
return { type: 'const', const: '' };
if (expressions.length === 1)
return expressions0;
return { type: 'and', expr: expressions };
}
/ Parses a pattern and returns an expression tree /
function Parse(pattern) {
if (IsGroup(pattern))
return Parse(InGroup(pattern));
if (IsPrecedenceOr(pattern))
return Or(pattern);
if (IsPrecedenceAnd(pattern))
return And(pattern);
return { type: 'const', const: pattern };
}
TemplateLiteralParser.Parse = Parse;
/ Parses a pattern and strips forward and trailing ^ and $ /
function ParseExact(pattern) {
return Parse(pattern.slice(1, pattern.length - 1));
}
TemplateLiteralParser.ParseExact = ParseExact;
})(TemplateLiteralParser = exports.TemplateLiteralParser || (exports.TemplateLiteralParser = {}));
// --------------------------------------------------------------------------------------
// TemplateLiteralFinite
// --------------------------------------------------------------------------------------
var TemplateLiteralFinite;
(function (TemplateLiteralFinite) {
function IsNumber(expression) {
// prettier-ignore
return (expression.type === 'or' &&
expression.expr.length === 2 &&
expression.expr0.type === 'const' &&
expression.expr0.const === '0' &&
expression.expr[1].type === 'const' &&
expression.expr[1].const === '[1-9][0-9]');
}
function IsBoolean(expression) {
// prettier-ignore
return (expression.type === 'or' &&
expression.expr.length === 2 &&
expression.expr0.type === 'const' &&
expression.expr0.const === 'true' &&
expression.expr[1].type === 'const' &&
expression.expr[1].const === 'false');
}
function IsString(expression) {
return expression.type === 'const' && expression.const === '.';
}
function Check(expression) {
if (IsBoolean(expression))
return true;
if (IsNumber(expression) || IsString(expression))
return false;
if (expression.type === 'and')
return expression.expr.every((expr) => Check(expr));
if (expression.type === 'or')
return expression.expr.every((expr) => Check(expr));
if (expression.type === 'const')
return true;
throw Error(TemplateLiteralFinite: Unknown expression type);
}
TemplateLiteralFinite.Check = Check;
})(TemplateLiteralFinite = exports.TemplateLiteralFinite || (exports.TemplateLiteralFinite = {}));
// --------------------------------------------------------------------------------------
// TemplateLiteralGenerator
// --------------------------------------------------------------------------------------
var TemplateLiteralGenerator;
(function (TemplateLiteralGenerator) {
function Reduce(buffer) {
if (buffer.length === 1)
return yield buffer0;
for (const left of buffer0) {
for (const right of Reduce(buffer.slice(1))) {
yield ${left}${right};
}
}
}
function And(expression) {
return yield Reduce(expression.expr.map((expr) => [...Generate(expr)]));
}
function Or(expression) {
for (const expr of expression.expr)
yield Generate(expr);
}
function Const(expression) {
return yield expression.const;
}
function Generate(expression) {
if (expression.type === 'and')
return yield And(expression);
if (expression.type === 'or')
return yield Or(expression);
if (expression.type === 'const')
return yield Const(expression);
throw Error('TemplateLiteralGenerator: Unknown expression');
}
TemplateLiteralGenerator.Generate = Generate;
})(TemplateLiteralGenerator = exports.TemplateLiteralGenerator || (exports.TemplateLiteralGenerator = {}));
// --------------------------------------------------------------------------
// TypeOrdinal: Used for auto $id generation
// --------------------------------------------------------------------------
let TypeOrdinal = 0;
// --------------------------------------------------------------------------
// TypeBuilder
// --------------------------------------------------------------------------
class TypeBuilder {
/ [Utility] Creates a schema without static and params types /
Create(schema) {
return schema;
}
/ [Standard] Omits compositing symbols from this schema */
Strict(schema) {
return JSON.parse(JSON.stringify(schema));
}
}
exports.TypeBuilder = TypeBuilder;
// --------------------------------------------------------------------------
// StandardTypeBuilder
// --------------------------------------------------------------------------
class StandardTypeBuilder extends TypeBuilder {
// ------------------------------------------------------------------------
// Modifiers
// ------------------------------------------------------------------------
/ [Modifier] Creates a Optional property /
Optional(schema) {
return { [exports.Modifier]: 'Optional', ...TypeClone.Clone(schema, {}) };
}
/ [Modifier] Creates a ReadonlyOptional property /
ReadonlyOptional(schema) {
return { [exports.Modifier]: 'ReadonlyOptional', ...TypeClone.Clone(schema, {}) };
}
/ [Modifier] Creates a Readonly object or property */
Readonly(schema) {
return { [exports.Modifier]: 'Readonly', ...schema };
}
// ------------------------------------------------------------------------
// Types
// ------------------------------------------------------------------------
/ [Standard] Creates an Any type /
Any(options = {}) {
return this.Create({ ...options, [exports.Kind]: 'Any' });
}
/ [Standard] Creates an Array type /
Array(items, options = {}) {
return this.Create({ ...options, [exports.Kind]: 'Array', type: 'array', items: TypeClone.Clone(items, {}) });
}
/ [Standard] Creates a Boolean type */
Boolean(options = {}) {
return this.Create({ ...options, [exports.Kind]: 'Boolean', type: 'boolean' });
}
/ [Standard] Creates a Composite object type. /
Composite(objects, options) {
const isOptionalAll = (objects, key) => objects.every((object) => !(key in object.properties) || IsOptional(object.properties[key]));
const IsOptional = (schema) => TypeGuard.TOptional(schema) || TypeGuard.TReadonlyOptional(schema);
const [required, optional] = [new Set(), new Set()];
for (const object of objects) {
for (const key of globalThis.Object.getOwnPropertyNames(object.properties)) {
if (isOptionalAll(objects, key))
optional.add(key);
}
}
for (const object of objects) {
for (const key of globalThis.Object.getOwnPropertyNames(object.properties)) {
if (!optional.has(key))
required.add(key);
}
}
const properties = {};
for (const object of objects) {
for (const [key, schema] of Object.entries(object.properties)) {
const property = TypeClone.Clone(schema, {});
if (!optional.has(key))
delete property[exports.Modifier];
if (key in properties) {
const left = TypeExtends.Extends(properties[key], property) !== TypeExtendsResult.False;
const right = TypeExtends.Extends(property, properties[key]) !== TypeExtendsResult.False;
if (!left && !right)
properties[key] = exports.Type.Never();
if (!left && right)
properties[key] = property;
}
else {
properties[key] = property;
}
}
}
if (required.size > 0) {
return this.Create({ ...options, [exports.Kind]: 'Object', [exports.Hint]: 'Composite', type: 'object', properties, required: [...required] });
}
else {
return this.Create({ ...options, [exports.Kind]: 'Object', [exports.Hint]: 'Composite', type: 'object', properties });
}
}
/ [Standard] Creates a Enum type /
Enum(item, options = {}) {
// prettier-ignore
const values = globalThis.Object.keys(item).filter((key) => isNaN(key)).map((key) => item[key]);
const anyOf = values.map((value) => (typeof value === 'string' ? { [exports.Kind]: 'Literal', type: 'string', const: value } : { [exports.Kind]: 'Literal', type: 'number', const: value }));
return this.Create({ ...options, [exports.Kind]: 'Union', anyOf });
}
/ [Standard] A conditional type expression that will return the true type if the left type extends the right */
Extends(left, right, trueType, falseType, options = {}) {
switch (TypeExtends.Extends(left, right)) {
case TypeExtendsResult.Union:
return this.Union([TypeClone.Clone(trueType, options), TypeClone.Clone(falseType, options)]);
case TypeExtendsResult.True:
return TypeClone.Clone(trueType, options);
case TypeExtendsResult.False:
return TypeClone.Clone(falseType, options);
}
}
/ [Standard] Excludes from the left type any type that is not assignable to the right /
Exclude(left, right, options = {}) {
if (TypeGuard.TTemplateLiteral(left))
return this.Exclude(TemplateLiteralResolver.Resolve(left), right, options);
if (TypeGuard.TTemplateLiteral(right))
return this.Exclude(left, TemplateLiteralResolver.Resolve(right), options);
if (TypeGuard.TUnion(left)) {
const narrowed = left.anyOf.filter((inner) => TypeExtends.Extends(inner, right) === TypeExtendsResult.False);
return (narrowed.length === 1 ? TypeClone.Clone(narrowed0, options) : this.Union(narrowed, options));
}
else {
return (TypeExtends.Extends(left, right) !== TypeExtendsResult.False ? this.Never(options) : TypeClone.Clone(left, options));
}
}
/ [Standard] Extracts from the left type any type that is assignable to the right /
Extract(left, right, options = {}) {
if (TypeGuard.TTemplateLiteral(left))
return this.Extract(TemplateLiteralResolver.Resolve(left), right, options);
if (TypeGuard.TTemplateLiteral(right))
return this.Extract(left, TemplateLiteralResolver.Resolve(right), options);
if (TypeGuard.TUnion(left)) {
const narrowed = left.anyOf.filter((inner) => TypeExtends.Extends(inner, right) !== TypeExtendsResult.False);
return (narrowed.length === 1 ? TypeClone.Clone(narrowed0, options) : this.Union(narrowed, options));
}
else {
return (TypeExtends.Extends(left, right) !== TypeExtendsResult.False ? TypeClone.Clone(left, options) : this.Never(options));
}
}
/ [Standard] Creates an Integer type */
Integer(options = {}) {
return this.Create({ ...options, [exports.Kind]: 'Integer', type: 'integer' });
}
Intersect(allOf, options = {}) {
if (allOf.length === 0)
return exports.Type.Never();
if (allOf.length === 1)
return TypeClone.Clone(allOf0, options);
const objects = allOf.every((schema) => TypeGuard.TObject(schema));
const cloned = allOf.map((schema) => TypeClone.Clone(schema, {}));
const clonedUnevaluatedProperties = TypeGuard.TSchema(options.unevaluatedProperties) ? { unevaluatedProperties: TypeClone.Clone(options.unevaluatedProperties, {}) } : {};
if (options.unevaluatedProperties === false || TypeGuard.TSchema(options.unevaluatedProperties) || objects) {
return this.Create({ ...options, ...clonedUnevaluatedProperties, [exports.Kind]: 'Intersect', type: 'object', allOf: cloned });
}
else {
return this.Create({ ...options, ...clonedUnevaluatedProperties, [exports.Kind]: 'Intersect', allOf: cloned });
}
}
/ [Standard] Creates a KeyOf type /
KeyOf(schema, options = {}) {
if (TypeGuard.TRecord(schema)) {
const pattern = Object.getOwnPropertyNames(schema.patternProperties)0;
if (pattern === exports.PatternNumberExact)
return this.Number(options);
if (pattern === exports.PatternStringExact)
return this.String(options);
throw Error('StandardTypeBuilder: Unable to resolve key type from Record key pattern');
}
else {
const resolved = KeyResolver.Resolve(schema);
if (resolved.length === 0)
return this.Never(options);
const literals = resolved.map((key) => this.Literal(key));
return this.Union(literals, options);
}
}
/ [Standard] Creates a Literal type /
Literal(value, options = {}) {
return this.Create({ ...options, [exports.Kind]: 'Literal', const: value, type: typeof value });
}
/ [Standard] Creates a Never type */
Never(options = {}) {
return this.Create({ ...options, [exports.Kind]: 'Never', not: {} });
}
/ [Standard] Creates a Not type. The first argument is the disallowed type, the second is the allowed. /
Not(not, schema, options) {
return this.Create({ ...options, [exports.Kind]: 'Not', allOf: [{ not: TypeClone.Clone(not, {}) }, TypeClone.Clone(schema, {})] });
}
/ [Standard] Creates a Null type /
Null(options = {}) {
return this.Create({ ...options, [exports.Kind]: 'Null', type: 'null' });
}
/ [Standard] Creates a Number type */
Number(options = {}) {
return this.Create({ ...options, [exports.Kind]: 'Number', type: 'number' });
}
/ [Standard] Creates an Object type /
Object(properties, options = {}) {
const propertyKeys = globalThis.Object.getOwnPropertyNames(properties);
const optionalKeys = propertyKeys.filter((key) => TypeGuard.TOptional(properties[key]) || TypeGuard.TReadonlyOptional(properties[key]));
const requiredKeys = propertyKeys.filter((name) => !optionalKeys.includes(name));
const clonedAdditionalProperties = TypeGuard.TSchema(options.additionalProperties) ? { additionalProperties: TypeClone.Clone(options.additionalProperties, {}) } : {};
const clonedProperties = propertyKeys.reduce((acc, key) => ({ ...acc, [key]: TypeClone.Clone(properties[key], {}) }), {});
if (requiredKeys.length > 0) {
return this.Create({ ...options, ...clonedAdditionalProperties, [exports.Kind]: 'Object', type: 'object', properties: clonedProperties, required: requiredKeys });
}
else {
return this.Create({ ...options, ...clonedAdditionalProperties, [exports.Kind]: 'Object', type: 'object', properties: clonedProperties });
}
}
Omit(schema, unresolved, options = {}) {
// prettier-ignore
const keys = TypeGuard.TUnionLiteral(unresolved) ? unresolved.anyOf.map((schema) => schema.const) :
TypeGuard.TLiteral(unresolved) ? [unresolved.const] :
TypeGuard.TNever(unresolved) ? [] :
unresolved;
// prettier-ignore
return ObjectMap.Map(TypeClone.Clone(schema, {}), (schema) => {
if (schema.required) {
schema.required = schema.required.filter((key) => !keys.includes(key));
if (schema.required.length === 0)
delete schema.required;
}
for (const key of globalThis.Object.keys(schema.properties)) {
if (keys.includes(key))
delete schema.properties[key];
}
return this.Create(schema);
}, options);
}
/ [Standard] Creates a mapped type where all properties are Optional /
Partial(schema, options = {}) {
function Apply(schema) {
// prettier-ignore
switch (schema[exports.Modifier]) {
case 'ReadonlyOptional':
schema[exports.Modifier] = 'ReadonlyOptional';
break;
case 'Readonly':
schema[exports.Modifier] = 'ReadonlyOptional';
break;
case 'Optional':
schema[exports.Modifier] = 'Optional';
break;
default:
schema[exports.Modifier] = 'Optional';
break;
}
}
// prettier-ignore
return ObjectMap.Map(TypeClone.Clone(schema, {}), (schema) => {
delete schema.required;
globalThis.Object.keys(schema.properties).forEach(key => Apply(schema.properties[key]));
return schema;
}, options);
}
Pick(schema, unresolved, options = {}) {
// prettier-ignore
const keys = TypeGuard.TUnionLiteral(unresolved) ? unresolved.anyOf.map((schema) => schema.const) :
TypeGuard.TLiteral(unresolved) ? [unresolved.const] :
TypeGuard.TNever(unresolved) ? [] :
unresolved;
// prettier-ignore
return ObjectMap.Map(TypeClone.Clone(schema, {}), (schema) => {
if (schema.required) {
schema.required = schema.required.filter((key) => keys.includes(key));
if (schema.required.length === 0)
delete schema.required;
}
for (const key of globalThis.Object.keys(schema.properties)) {
if (!keys.includes(key))
delete schema.properties[key];
}
return this.Create(schema);
}, options);
}
/ [Standard] Creates a Record type */
Record(key, schema, options = {}) {
if (TypeGuard.TTemplateLiteral(key)) {
const expression = TemplateLiteralParser.ParseExact(key.pattern);
// prettier-ignore
return TemplateLiteralFinite.Check(expression)
? (this.Object([...TemplateLiteralGenerator.Generate(expression)].reduce((acc, key) => ({ ...acc, [key]: TypeClone.Clone(schema, {}) }), {}), options))
: this.Create({ ...options, [exports.Kind]: 'Record', type: 'object', patternProperties: { [key.pattern]: TypeClone.Clone(schema, {}) }, additionalProperties: false });
}
else if (TypeGuard.TUnionLiteral(key)) {
if (key.anyOf.every((schema) => TypeGuard.TLiteral(schema) && (typeof schema.const === 'string' || typeof schema.const === 'number'))) {
const properties = key.anyOf.reduce((acc, literal) => ({ ...acc, [literal.const]: TypeClone.Clone(schema, {}) }), {});
return this.Object(properties, { ...options, [exports.Hint]: 'Record' });
}
else
throw Error('TypeBuilder: Record key can only be derived from union literal of number or string');
}
else if (TypeGuard.TLiteral(key)) {
if (typeof key.const === 'string' || typeof key.const === 'number') {
return this.Object({ [key.const]: TypeClone.Clone(schema, {}) }, options);
}
else
throw Error('TypeBuilder: Record key can only be derived from literals of number or string');
}
else if (TypeGuard.TInteger(key) || TypeGuard.TNumber(key)) {
const pattern = exports.PatternNumberExact;
return this.Create({ ...options, [exports.Kind]: 'Record', type: 'object', patternProperties: { [pattern]: TypeClone.Clone(schema, {}) }, additionalProperties: false });
}
else if (TypeGuard.TString(key)) {
const pattern = key.pattern === undefined ? exports.PatternStringExact : key.pattern;
return this.Create({ ...options, [exports.Kind]: 'Record', type: 'object', patternProperties: { [pattern]: TypeClone.Clone(schema, {}) }, additionalProperties: false });
}
else {
throw Error(StandardTypeBuilder: Invalid Record Key);
}
}
/ [Standard] Creates a Recursive type /
Recursive(callback, options = {}) {
if (options.$id === undefined)
options.$id = T${TypeOrdinal++};
const thisType = callback({ [exports.Kind]: 'This', $ref: ${options.$id} });
thisType.$id = options.$id;
return this.Create({ ...options, [exports.Hint]: 'Recursive', ...thisType });
}
/ [Standard] Creates a Ref type. The referenced type must contain a $id /
Ref(schema, options = {}) {
if (schema.$id === undefined)
throw Error('StandardTypeBuilder.Ref: Target type must specify an $id');
return this.Create({ ...options, [exports.Kind]: 'Ref', $ref: schema.$id });
}
/ [Standard] Creates a mapped type where all properties are Required */
Required(schema, options = {}) {
function Apply(schema) {
// prettier-ignore
switch (schema[exports.Modifier]) {
case 'ReadonlyOptional':
schema[exports.Modifier] = 'Readonly';
break;
case 'Readonly':
schema[exports.Modifier] = 'Readonly';
break;
case 'Optional':
delete schema[exports.Modifier];
break;
default:
delete schema[exports.Modifier];
break;
}
}
// prettier-ignore
return ObjectMap.Map(TypeClone.Clone(schema, {}), (schema) => {
schema.required = globalThis.Object.keys(schema.properties);
globalThis.Object.keys(schema.properties).forEach(key => Apply(schema.properties[key]));
return schema;
}, options);
}
/ [Standard] Creates a String type /
String(options = {}) {
return this.Create({ ...options, [exports.Kind]: 'String', type: 'string' });
}
/ [Standard] Creates a template literal type /
TemplateLiteral(kinds, options = {}) {
const pattern = TemplateLiteralPattern.Create(kinds);
return this.Create({ ...options, [exports.Kind]: 'TemplateLiteral', type: 'string', pattern });
}
/ [Standard] Creates a Tuple type */
Tuple(items, options = {}) {
const [additionalItems, minItems, maxItems] = [false, items.length, items.length];
const clonedItems = items.map((item) => TypeClone.Clone(item, {}));
// prettier-ignore
const schema = (items.length > 0 ?
{ ...options, [exports.Kind]: 'Tuple', type: 'array', items: clonedItems, additionalItems, minItems, maxItems } :
{ ...options, [exports.Kind]: 'Tuple', type: 'array', minItems, maxItems });
return this.Create(schema);
}
Union(union, options = {}) {
if (TypeGuard.TTemplateLiteral(union)) {
return TemplateLiteralResolver.Resolve(union);
}
else {
const anyOf = union;
if (anyOf.length === 0)
return this.Never(options);
if (anyOf.length === 1)
return this.Create(TypeClone.Clone(anyOf0, options));
const clonedAnyOf = anyOf.map((schema) => TypeClone.Clone(schema, {}));
return this.Create({ ...options, [exports.Kind]: 'Union', anyOf: clonedAnyOf });
}
}
/ [Standard] Creates an Unknown type /
Unknown(options = {}) {
return this.Create({ ...options, [exports.Kind]: 'Unknown' });
}
/ [Standard] Creates a Unsafe type that infers for the generic argument /
Unsafe(options = {}) {
return this.Create({ ...options, [exports.Kind]: options[exports.Kind] || 'Unsafe' });
}
}
exports.StandardTypeBuilder = StandardTypeBuilder;
// --------------------------------------------------------------------------
// ExtendedTypeBuilder
// --------------------------------------------------------------------------
class ExtendedTypeBuilder extends StandardTypeBuilder {
/ [Extended] Creates a BigInt type */
BigInt(options = {}) {
return this.Create({ ...options, [exports.Kind]: 'BigInt', type: 'null', typeOf: 'BigInt' });
}
/ [Extended] Extracts the ConstructorParameters from the given Constructor type /
ConstructorParameters(schema, options = {}) {
return this.Tuple([...schema.parameters], { ...options });
}
Constructor(parameters, returns, options = {}) {
const clonedReturns = TypeClone.Clone(returns, {});
if (TypeGuard.TTuple(parameters)) {
const clonedParameters = parameters.items === undefined ? [] : parameters.items.map((parameter) => TypeClone.Clone(parameter, {}));
return this.Create({ ...options, [exports.Kind]: 'Constructor', type: 'object', instanceOf: 'Constructor', parameters: clonedParameters, returns: clonedReturns });
}
else if (globalThis.Array.isArray(parameters)) {
const clonedParameters = parameters.map((parameter) => TypeClone.Clone(parameter, {}));
return this.Create({ ...options, [exports.Kind]: 'Constructor', type: 'object', instanceOf: 'Constructor', parameters: clonedParameters, returns: clonedReturns });
}
else {
throw new Error('ExtendedTypeBuilder.Constructor: Invalid parameters');
}
}
/ [Extended] Creates a Date type /
Date(options = {}) {
return this.Create({ ...options, [exports.Kind]: 'Date', type: 'object', instanceOf: 'Date' });
}
Function(parameters, returns, options = {}) {
const clonedReturns = TypeClone.Clone(returns, {});
if (TypeGuard.TTuple(parameters)) {
const clonedParameters = parameters.items === undefined ? [] : parameters.items.map((parameter) => TypeClone.Clone(parameter, {}));
return this.Create({ ...options, [exports.Kind]: 'Function', type: 'object', instanceOf: 'Function', parameters: clonedParameters, returns: clonedReturns });
}
else if (globalThis.Array.isArray(parameters)) {
const clonedParameters = parameters.map((parameter) => TypeClone.Clone(parameter, {}));
return this.Create({ ...options, [exports.Kind]: 'Function', type: 'object', instanceOf: 'Function', parameters: clonedParameters, returns: clonedReturns });
}
else {
throw new Error('ExtendedTypeBuilder.Function: Invalid parameters');
}
}
/ [Extended] Extracts the InstanceType from the given Constructor */
InstanceType(schema, options = {}) {
return TypeClone.Clone(schema.returns, options);
}
/ [Extended] Extracts the Parameters from the given Function type /
Parameters(schema, options = {}) {
return this.Tuple(schema.parameters, { ...options });
}
/ [Extended] Creates a Promise type /
Promise(item, options = {}) {
return this.Create({ ...options, [exports.Kind]: 'Promise', type: 'object', instanceOf: 'Promise', item: TypeClone.Clone(item, {}) });
}
/ [Extended] Creates a regular expression type */
RegEx(regex, options = {}) {
return this.Create({ ...options, [exports.Kind]: 'String', type: 'string', pattern: regex.source });
}
/ [Extended] Extracts the ReturnType from the given Function /
ReturnType(schema, options = {}) {
return TypeClone.Clone(schema.returns, options);
}
/ [Extended] Creates a Symbol type /
Symbol(options) {
return this.Create({ ...options, [exports.Kind]: 'Symbol', type: 'null', typeOf: 'Symbol' });
}
/ [Extended] Creates a Undefined type */
Undefined(options = {}) {
return this.Create({ ...options, [exports.Kind]: 'Undefined', type: 'null', typeOf: 'Undefined' });
}
/ [Extended] Creates a Uint8Array type /
Uint8Array(options = {}) {
return this.Create({ ...options, [exports.Kind]: 'Uint8Array', type: 'object', instanceOf: 'Uint8Array' });
}
/ [Extended] Creates a Void type /
Void(options = {}) {
return this.Create({ ...options, [exports.Kind]: 'Void', type: 'null', typeOf: 'Void' });
}
}
exports.ExtendedTypeBuilder = ExtendedTypeBuilder;
/** JSON Schema TypeBuilder with Static Resolution for TypeScript
Type
Source: my-backend/node_modules/@sinclair/typebox/typebox.js
Signature: Type(= new ExtendedTypeBuilder()
JSDoc:
JSON Schema TypeBuilder with Static Resolution for TypeScript
wrap
Source: my-backend/node_modules/@sinonjs/commons/lib/deprecated.js
Signature: wrap(= function (func, msg)
JSDoc:
Returns a function that will invoke the supplied function and print a deprecation warning to the console each time it is called. @param {Function} func @param {string} msg @returns {Function}
defaultMsg
Source: my-backend/node_modules/@sinonjs/commons/lib/deprecated.js
Signature: defaultMsg(= function (packageName, funcName)
JSDoc:
Returns a string which can be supplied to wrap() to notify the user that a
particular part of the sinon API has been deprecated.
@param {string} packageName
@param {string} funcName
@returns {string}
printWarning
Source: my-backend/node_modules/@sinonjs/commons/lib/deprecated.js
Signature: printWarning(= function (msg)
JSDoc:
Prints a warning on the console, when it exists @param {string} msg @returns {undefined}
transform
Source: my-backend/node_modules/@types/babel__core/index.d.ts
Signature: transform(code: string, callback: FileResultCallback)
JSDoc:
Source map standard format as to revision 3 @see {@link https://sourcemaps.info/spec.html} @see {@link https://github.com/mozilla/source-map/blob/HEAD/source-map.d.ts} / interface InputSourceMap { version: number; sources: string[]; names: string[]; sourceRoot?: string | undefined; sourcesContent?: string[] | undefined; mappings: string; file: string; }
export interface TransformOptions {
/
Specify which assumptions it can make about your code, to better optimize the compilation result. NOTE**: This replaces the various loose options in plugins in favor of
top-level options that can apply to multiple plugins
@see https://babeljs.io/docs/en/assumptions / assumptions?: { name: string: boolean } | null | undefined;
/**
Include the AST in the returned object
Default: false
/
ast?: boolean | null | undefined;
/**
Attach a comment after all non-user injected code
Default: null
/
auxiliaryCommentAfter?: string | null | undefined;
/**
Attach a comment before all non-user injected code
Default: null
/
auxiliaryCommentBefore?: string | null | undefined;
/**
Specify the "root" folder that defines the location to search for "babel.config.js", and the default folder to allow .babelrc files inside of.
Default: "."
/
root?: string | null | undefined;
/**
This option, combined with the "root" value, defines how Babel chooses its project root. The different modes define different ways that Babel can process the "root" value to get the final project root.
@see https://babeljs.io/docs/en/next/options#rootmode / rootMode?: "root" | "upward" | "upward-optional" | undefined;
/**
The config file to load Babel's config from. Defaults to searching for "babel.config.js" inside the "root" folder. false will disable searching for config files.
Default: undefined
/
configFile?: string | boolean | null | undefined;
/**
Specify whether or not to use .babelrc and .babelignore files.
Default: true
/
babelrc?: boolean | null | undefined;
/**
Specify which packages should be search for .babelrc files when they are being compiled. true to always search, or a path string or an array of paths to packages to search
inside of. Defaults to only searching the "root" package.
Default: (root)
/
babelrcRoots?: boolean | MatchPattern | MatchPattern[] | null | undefined;
/**
Toggles whether or not browserslist config sources are used, which includes searching for any browserslist files or referencing the browserslist key inside package.json. This is useful for projects that use a browserslist config for files that won't be compiled with Babel.
If a string is specified, it must represent the path of a browserslist configuration file. Relative paths are resolved relative to the configuration file which specifies
this option, or to cwd when it's passed as part of the programmatic options.
Default: true
/
browserslistConfigFile?: boolean | null | undefined;
/**
The Browserslist environment to use.
Default: undefined
/
browserslistEnv?: string | null | undefined;
/**
By default babel.transformFromAst will clone the input AST to avoid mutations.
Specifying cloneInputAst: false can improve parsing performance if the input AST is not used elsewhere.
Default: true
/
cloneInputAst?: boolean | null | undefined;
/**
Defaults to environment variable BABEL_ENV if set, or else NODE_ENV if set, or else it defaults to "development"
Default: env vars / envName?: string | undefined;
/**
If any of patterns match, the current configuration object is considered inactive and is ignored during config processing. / exclude?: MatchPattern | MatchPattern[] | undefined;
/**
Enable code generation
Default: true
/
code?: boolean | null | undefined;
/**
Output comments in generated output
Default: true
/
comments?: boolean | null | undefined;
/**
Do not include superfluous whitespace characters and line terminators. When set to "auto" compact is set to true on input sizes of >500KB
Default: "auto"
/
compact?: boolean | "auto" | null | undefined;
/**
The working directory that Babel's programmatic options are loaded relative to.
Default: "."
/
cwd?: string | null | undefined;
/**
Utilities may pass a caller object to identify themselves to Babel and pass capability-related flags for use by configs, presets and plugins.
@see https://babeljs.io/docs/en/next/options#caller / caller?: TransformCaller | undefined;
/**
This is an object of keys that represent different environments. For example, you may have: { env: { production: { \/* specific options *\/ } } }
which will use those options when the envName is production
Default: {}
/
env?: { [index: string]: TransformOptions | null | undefined } | null | undefined;
/**
A path to a .babelrc file to extend
Default: null
/
extends?: string | null | undefined;
/**
Filename for use in errors etc
Default: "unknown"
/
filename?: string | null | undefined;
/**
Filename relative to sourceRoot
Default: (filename)
/
filenameRelative?: string | null | undefined;
/**
An object containing the options to be passed down to the babel code generator, @babel/generator
Default: {}
/
generatorOpts?: GeneratorOptions | null | undefined;
/**
Specify a custom callback to generate a module id with. Called as getModuleId(moduleName). If falsy value is returned then the generated module id is used
Default: null
/
getModuleId?: ((moduleName: string) => string | null | undefined) | null | undefined;
/**
ANSI highlight syntax error code frames
Default: true
/
highlightCode?: boolean | null | undefined;
/**
Opposite to the only option. ignore is disregarded if only is specified
Default: null
/
ignore?: MatchPattern[] | null | undefined;
/**
This option is a synonym for "test" / include?: MatchPattern | MatchPattern[] | undefined;
/**
A source map object that the output source map will be based on
Default: null
/
inputSourceMap?: InputSourceMap | null | undefined;
/**
Should the output be minified (not printing last semicolons in blocks, printing literal string values instead of escaped ones, stripping () from new when safe)
Default: false
/
minified?: boolean | null | undefined;
/**
Specify a custom name for module ids
Default: null
/
moduleId?: string | null | undefined;
/**
If truthy, insert an explicit id for modules. By default, all modules are anonymous. (Not available for common modules)
Default: false
/
moduleIds?: boolean | null | undefined;
/**
Optional prefix for the AMD module formatter that will be prepend to the filename on module definitions
Default: (sourceRoot)
/
moduleRoot?: string | null | undefined;
/**
A glob, regex, or mixed array of both, matching paths to only compile. Can also be an array of arrays containing paths to explicitly match. When attempting to compile a non-matching file it's returned verbatim
Default: null
/
only?: MatchPattern[] | null | undefined;
/**
Allows users to provide an array of options that will be merged into the current configuration one at a time. This feature is best used alongside the "test"/"include"/"exclude" options to provide conditions for which an override should apply / overrides?: TransformOptions[] | undefined;
/**
An object containing the options to be passed down to the babel parser, @babel/parser
Default: {}
/
parserOpts?: ParserOptions | null | undefined;
/**
List of plugins to load and use
Default: []
/
plugins?: PluginItem[] | null | undefined;
/**
List of presets (a set of plugins) to load and use
Default: []
/
presets?: PluginItem[] | null | undefined;
/**
Retain line numbers. This will lead to wacky code but is handy for scenarios where you can't use source maps. (NOTE: This will not retain the columns)
Default: false
/
retainLines?: boolean | null | undefined;
/**
An optional callback that controls whether a comment should be output or not. Called as shouldPrintComment(commentContents). NOTE: This overrides the comment option when used
Default: null
/
shouldPrintComment?: ((commentContents: string) => boolean) | null | undefined;
/**
Set sources[0] on returned source map
Default: (filenameRelative)
/
sourceFileName?: string | null | undefined;
/**
If truthy, adds a map property to returned output. If set to "inline", a comment with a sourceMappingURL directive is added to the bottom of the returned code. If set to "both"
then a map property is returned as well as a source map comment appended. This does not emit sourcemap files by itself!
Default: false
/
sourceMaps?: boolean | "inline" | "both" | null | undefined;
/**
The root from which all sources are relative
Default: (moduleRoot)
/
sourceRoot?: string | null | undefined;
/**
Indicate the mode the code should be parsed in. Can be one of "script", "module", or "unambiguous". "unambiguous" will make Babel attempt to guess, based on the presence of ES6
import or export statements. Files with ES6 imports and exports are considered "module" and are otherwise "script".
Default: ("module")
/
sourceType?: "script" | "module" | "unambiguous" | null | undefined;
/**
If all patterns fail to match, the current configuration object is considered inactive and is ignored during config processing. / test?: MatchPattern | MatchPattern[] | undefined;
/**
Describes the environments you support/target for your project. This can either be a browserslist-compatible query (with caveats)
Default: {}
/
targets?:
| string
| string[]
| {
esmodules?: boolean;
node?: Omit
/**
An optional callback that can be used to wrap visitor methods. NOTE: This is useful for things like introspection, and not really needed for implementing anything. Called as
wrapPluginVisitorMethod(pluginAlias, visitorType, callback).
/
wrapPluginVisitorMethod?:
| ((
pluginAlias: string,
visitorType: "enter" | "exit",
callback: (path: NodePath, state: any) => void,
) => (path: NodePath, state: any) => void)
| null
| undefined;
}
export interface TransformCaller {
// the only required property
name: string;
// e.g. set to true by babel-loader and false by babel-jest
supportsStaticESM?: boolean | undefined;
supportsDynamicImport?: boolean | undefined;
supportsExportNamespaceFrom?: boolean | undefined;
supportsTopLevelAwait?: boolean | undefined;
// augment this with a "declare module '@babel/core' { ... }" if you need more keys
}
export type FileResultCallback = (err: Error | null, result: BabelFileResult | null) => any;
export interface MatchPatternContext { envName: string; dirname: string; caller: TransformCaller | undefined; } export type MatchPattern = string | RegExp | ((filename: string | undefined, context: MatchPatternContext) => boolean);
/** Transforms the passed in code. Calling a callback with an object with the generated code, source map, and AST.
transform
Source: my-backend/node_modules/@types/babel__core/index.d.ts
Signature: transform(code: string, opts: TransformOptions | undefined, callback: FileResultCallback)
JSDoc:
Transforms the passed in code. Calling a callback with an object with the generated code, source map, and AST.
transform
Source: my-backend/node_modules/@types/babel__core/index.d.ts
Signature: transform(code: string, opts?: TransformOptions)
JSDoc:
Here for backward-compatibility. Ideally use transformSync if you want a synchronous API.
transformSync
Source: my-backend/node_modules/@types/babel__core/index.d.ts
Signature: transformSync(code: string, opts?: TransformOptions)
JSDoc:
Transforms the passed in code. Returning an object with the generated code, source map, and AST.
transformAsync
Source: my-backend/node_modules/@types/babel__core/index.d.ts
Signature: transformAsync(code: string, opts?: TransformOptions)
JSDoc:
Transforms the passed in code. Calling a callback with an object with the generated code, source map, and AST.
transformFile
Source: my-backend/node_modules/@types/babel__core/index.d.ts
Signature: transformFile(filename: string, callback: FileResultCallback)
JSDoc:
Asynchronously transforms the entire contents of a file.
transformFile
Source: my-backend/node_modules/@types/babel__core/index.d.ts
Signature: transformFile(filename: string, opts: TransformOptions | undefined, callback: FileResultCallback)
JSDoc:
Asynchronously transforms the entire contents of a file.
transformFileSync
Source: my-backend/node_modules/@types/babel__core/index.d.ts
Signature: transformFileSync(filename: string, opts?: TransformOptions)
JSDoc:
Synchronous version of babel.transformFile. Returns the transformed contents of the filename.
transformFileAsync
Source: my-backend/node_modules/@types/babel__core/index.d.ts
Signature: transformFileAsync(filename: string, opts?: TransformOptions)
JSDoc:
Asynchronously transforms the entire contents of a file.
transformFromAst
Source: my-backend/node_modules/@types/babel__core/index.d.ts
Signature: transformFromAst(ast: Node, code: string | undefined, callback: FileResultCallback)
JSDoc:
Given an AST, transform it.
transformFromAst
Source: my-backend/node_modules/@types/babel__core/index.d.ts
Signature: transformFromAst(
ast: Node,
code: string | undefined,
opts: TransformOptions | undefined,
callback: FileResultCallback,
)
JSDoc:
Given an AST, transform it.
transformFromAstSync
Source: my-backend/node_modules/@types/babel__core/index.d.ts
Signature: transformFromAstSync(ast: Node, code?: string, opts?: TransformOptions)
JSDoc:
Here for backward-compatibility. Ideally use ".transformSync" if you want a synchronous API.
transformFromAstAsync
Source: my-backend/node_modules/@types/babel__core/index.d.ts
Signature: transformFromAstAsync(
ast: Node,
code?: string,
opts?: TransformOptions,
)
JSDoc:
Given an AST, transform it.
parse
Source: my-backend/node_modules/@types/babel__core/index.d.ts
Signature: parse(code: string, callback: FileParseCallback)
JSDoc:
Given some code, parse it using Babel's standard behavior. Referenced presets and plugins will be loaded such that optional syntax plugins are automatically enabled.
parse
Source: my-backend/node_modules/@types/babel__core/index.d.ts
Signature: parse(code: string, options: TransformOptions | undefined, callback: FileParseCallback)
JSDoc:
Given some code, parse it using Babel's standard behavior. Referenced presets and plugins will be loaded such that optional syntax plugins are automatically enabled.
parse
Source: my-backend/node_modules/@types/babel__core/index.d.ts
Signature: parse(code: string, options?: TransformOptions)
JSDoc:
Given some code, parse it using Babel's standard behavior. Referenced presets and plugins will be loaded such that optional syntax plugins are automatically enabled.
parseSync
Source: my-backend/node_modules/@types/babel__core/index.d.ts
Signature: parseSync(code: string, options?: TransformOptions)
JSDoc:
Given some code, parse it using Babel's standard behavior. Referenced presets and plugins will be loaded such that optional syntax plugins are automatically enabled.
parseAsync
Source: my-backend/node_modules/@types/babel__core/index.d.ts
Signature: parseAsync(code: string, options?: TransformOptions)
JSDoc:
Given some code, parse it using Babel's standard behavior. Referenced presets and plugins will be loaded such that optional syntax plugins are automatically enabled.
loadOptions
Source: my-backend/node_modules/@types/babel__core/index.d.ts
Signature: loadOptions(options?: TransformOptions)
JSDoc:
Resolve Babel's options fully, resulting in an options object where:
- opts.plugins is a full list of Plugin instances.
- opts.presets is empty and all presets are flattened into opts.
- It can be safely passed back to Babel. Fields like babelrc have been set to false so that later calls to Babel will not make a second attempt to load config files.
Plugin instances aren't meant to be manipulated directly, but often callers will serialize this opts to JSON to use it as a cache key representing the options Babel has received. Caching on this isn't 100% guaranteed to invalidate properly, but it is the best we have at the moment.
loadPartialConfig
Source: my-backend/node_modules/@types/babel__core/index.d.ts
Signature: loadPartialConfig(options?: TransformOptions)
JSDoc:
To allow systems to easily manipulate and validate a user's config, this function resolves the plugins and presets and proceeds no further. The expectation is that callers will take the config's .options, manipulate it as then see fit and pass it back to Babel again.
babelrc: string | void- The path of the.babelrcfile, if there was one.babelignore: string | void- The path of the.babelignorefile, if there was one.options: ValidatedOptions- The partially resolved options, which can be manipulated and passed back to Babel again.plugins: Array<ConfigItem>- See below.presets: Array<ConfigItem>- See below.- It can be safely passed back to Babel. Fields like
babelrchave been set to false so that later calls to Babel will not make a second attempt to load config files.
ConfigItem instances expose properties to introspect the values, but each item should be treated as
immutable. If changes are desired, the item should be removed from the list and replaced with either a normal
Babel config value, or with a replacement item created by babel.createConfigItem. See that function for
information about ConfigItem fields.
createConfigItem
Source: my-backend/node_modules/@types/babel__core/index.d.ts
Signature: createConfigItem(
value: PluginTarget | [PluginTarget, PluginOptions] | [PluginTarget, PluginOptions, string | undefined],
options?: CreateConfigItemOptions,
)
JSDoc:
The name that the user gave the plugin instance, e.g. plugins: [ ['env', {}, 'my-env'] ]
/
name?: string | undefined;
/**
The resolved value of the plugin. / value: object | ((...args: any[]) => any);
/**
The options object passed to the plugin. / options?: object | false | undefined;
/**
The path that the options are relative to. / dirname: string;
/**
Information about the plugin's file, if Babel knows it.
*
/
file?:
| {
/**
The file that the user requested, e.g. "@babel/env"
/
request: string;
/**
The full path of the resolved file, e.g. "/tmp/node_modules/@babel/preset-env/lib/index.js"
/
resolved: string;
}
| null
| undefined;
}
export type PluginOptions = object | undefined | false;
export type PluginTarget = string | object | ((...args: any[]) => any);
export type PluginItem =
| ConfigItem
| PluginObj
export function resolvePlugin(name: string, dirname: string): string | null; export function resolvePreset(name: string, dirname: string): string | null;
export interface CreateConfigItemOptions { dirname?: string | undefined; type?: "preset" | "plugin" | undefined; }
/** Allows build tooling to create and cache config items up front. If this function is called multiple times for a given plugin, Babel will call the plugin's function itself multiple times. If you have a clear set of expected plugins and presets to inject, pre-constructing the config items would be recommended.
generate
Source: my-backend/node_modules/@types/babel__generator/index.d.ts
Signature: generate(
ast: t.Node,
opts?: GeneratorOptions,
code?: string | { [filename: string]: string },
)
JSDoc:
Optional string to add as a block comment at the start of the output file. / auxiliaryCommentBefore?: string | undefined;
/**
Optional string to add as a block comment at the end of the output file. / auxiliaryCommentAfter?: string | undefined;
/**
Function that takes a comment (as a string) and returns true if the comment should be included in the output.
By default, comments are included if opts.comments is true or if opts.minifed is false and the comment
contains @preserve or @license.
/
shouldPrintComment?(comment: string): boolean;
/**
Attempt to use the same line numbers in the output code as in the source code (helps preserve stack traces).
Defaults to false.
/
retainLines?: boolean | undefined;
/**
Retain parens around function expressions (could be used to change engine parsing behavior)
Defaults to false.
/
retainFunctionParens?: boolean | undefined;
/**
Should comments be included in output? Defaults to true.
/
comments?: boolean | undefined;
/**
Set to true to avoid adding whitespace for formatting. Defaults to the value of opts.minified.
/
compact?: boolean | "auto" | undefined;
/**
Should the output be minified. Defaults to false.
/
minified?: boolean | undefined;
/**
Set to true to reduce whitespace (but not as much as opts.compact). Defaults to false.
/
concise?: boolean | undefined;
/**
Used in warning messages / filename?: string | undefined;
/**
Enable generating source maps. Defaults to false.
/
sourceMaps?: boolean | undefined;
/**
A root for all relative URLs in the source map. / sourceRoot?: string | undefined;
/**
The filename for the source code (i.e. the code in the code argument).
This will only be used if code is a string.
/
sourceFileName?: string | undefined;
/**
Set to true to run jsesc with "json": true to print "\u00A9" vs. "©"; / jsonCompatibleStrings?: boolean | undefined;
/**
Set to true to enable support for experimental decorators syntax before module exports.
Defaults to false.
/
decoratorsBeforeExport?: boolean | undefined;
/**
The import attributes/assertions syntax to use. When not specified, @babel/generator will try to match the style in the input code based on the AST shape. / importAttributesKeyword?: "with" | "assert" | "with-legacy";
/**
Options for outputting jsesc representation. / jsescOption?: { /** The default value for the quotes option is 'single'. This means that any occurrences of ' in the input string are escaped as \', so that the output can be used in a string literal wrapped in single quotes. / quotes?: "single" | "double" | "backtick" | undefined;
/**
The default value for the numbers option is 'decimal'. This means that any numeric values are represented using decimal integer literals. Other valid options are binary, octal, and hexadecimal, which result in binary integer literals, octal integer literals, and hexadecimal integer literals, respectively. / numbers?: "binary" | "octal" | "decimal" | "hexadecimal" | undefined;
/**
The wrap option takes a boolean value (true or false), and defaults to false (disabled). When enabled, the output is a valid JavaScript string literal wrapped in quotes. The type of quotes can be specified through the quotes setting. / wrap?: boolean | undefined;
/**
The es6 option takes a boolean value (true or false), and defaults to false (disabled). When enabled, any astral Unicode symbols in the input are escaped using ECMAScript 6 Unicode code point escape sequences instead of using separate escape sequences for each surrogate half. If backwards compatibility with ES5 environments is a concern, don’t enable this setting. If the json setting is enabled, the value for the es6 setting is ignored (as if it was false). / es6?: boolean | undefined;
/**
The escapeEverything option takes a boolean value (true or false), and defaults to false (disabled). When enabled, all the symbols in the output are escaped — even printable ASCII symbols. / escapeEverything?: boolean | undefined;
/**
The minimal option takes a boolean value (true or false), and defaults to false (disabled). When enabled, only a limited set of symbols in the output are escaped: \0, \b, \t, \n, \f, \r, \, \u2028, \u2029. / minimal?: boolean | undefined;
/**
The isScriptContext option takes a boolean value (true or false), and defaults to false (disabled). When enabled, occurrences of </script and </style in the output are escaped as <\/script and <\/style, and <!-- is escaped as \x3C!-- (or \u003C!-- when the json option is enabled). This setting is useful when jsesc’s output ends up as part of a